当前位置:网站首页>2021-05-07构造器
2021-05-07构造器
2022-06-23 09:55:00 【鹿其其鹿】
构造器讲解
类中的构造器也称为构造方法,是进行创建对象的时候必须要调用的,并且构造器有两个特点:
- 必须和类的名字相同
- 必须没有返回类型,也不能写void
一个类即使什么都不写,他也会存在一个构造方法
package oop.demo2;
//java编译之后会生成class文件
public class Person {
//一个类即使什么都不写也会存在一个方法
String name;
//构造器会实例化初始值
//使用new关键字,本质是在调用构造器
//
public Person(){
this.name = "qj";
}
//有参构造 一旦定义有参构造,无参构造就必须显示定义,否则new0实例化对象会报错
public Person(String name){
this.name = name;
}
}
package oop.demo2;
//一个项目应该只存在一个main方法
public class Application {
public static void main(String[]args){
//类:抽象的,实例化
//类实例化后会返回自己的对象
//student对象就是一个Student类的具体实例
Student xiaoming = new Student();
Student xiaohong = new Student();
xiaoming.name = "小明";
xiaohong.age = 18;
System.out.println(xiaoming.name);
System.out.println(xiaohong.age);
//new 实例化了一个对象
Person person = new Person();
System.out.println(person.name);
Person person1 = new Person("kuang");
System.out.println(person1.name);
}
}
构造器:
- 和类名相同
- 没有返回值
作用:
- new本质是在调用构造方法
- 初始化对象的值
注意点:
- 定义有参构造之后,如果想使用无参构造,要显示定义的一个无参构造
- Alt+Insert


边栏推荐
- 高性能算力中心 — NVMe/NVMe-oF — NVMe-oF Overview
- [GXYCTF2019]BabySQli
- 【CTF】bjdctf_2020_babyrop
- [geek challenge 2019] hardsql
- xml相关面试题
- 基於STM32設計的寵物投喂器
- 2022 gdevops global agile operation and maintenance summit - essence playback of Guangzhou station (with PPT download)
- Navagation navigation
- Install using snap in opencloudos NET 6
- Jump game of leetcode topic analysis
猜你喜欢

Use Base64 to show pictures

Lu Qi invests in quantum computing for the first time

2022 Gdevops全球敏捷运维峰会-广州站精华回放(附ppt下载)
![[geek Challenge 2019] hardsql](/img/73/ebfb410296b8e950c9ac0cf00adc17.png)
[geek Challenge 2019] hardsql
![[SUCTF 2019]CheckIn](/img/0e/75bb14e7a3e55ddc5126581a663bfb.png)
[SUCTF 2019]CheckIn

Is there anyone who plans to open source an industrial "seckill" system architecture?

Install the typescript environment and enable vscode to automatically monitor the compiled TS file as a JS file

基于STM32设计的宠物投喂器

构建信创产业生态,移动云立足全栈自主创新连放大招

Three methods to find the limit of univariate function -- lobida's rule and Taylor's formula
随机推荐
High performance computing center nvme / nvme of nvme of overview
Gorm advanced query
Successful experience in postgraduate entrance examination for MTI master of English translation major of Beijing University of science and technology in 2023
Sun Tower Technology recruits PostgreSQL Database Engineer
Jog sport mode
Go language JSON processing
RT-Thread 添加 msh 命令
[geek challenge 2019] hardsql
【CTF】 2018_rop
Find minimum in rotated sorted array
Go语言JSON 处理
Thin film interference data processing
2022 gdevops global agile operation and maintenance summit - essence playback of Guangzhou station (with PPT download)
Nuxt.js spa与ssr的区别
thymeleaf如何取url中请求参数值?
Go string comparison
Is there anyone who plans to open source an industrial "seckill" system architecture?
Game of life of leetcode topic analysis
太阳塔科技招聘PostgreSQL数据库工程师
利用华为云ECS服务器搭建安防视频监控平台