构造器的特点
1、必须和类的名字相同
2、必须没有返回类型,也不能写void
构造器作用
1、new本质在调用构造器(构造方法)
2、初始化对象的值
package com.jiemyx.oop.demo02;
public class Person {
//一个类即使什么都不写,它也会存在一个方法(构造器)
String name;
//显示定义构造器
//使用new关键字,本质是在调用构造器
/*public Person(){
this.name = "xiaoming";
}*/
//有参数的构造 一旦定义了有参构造,无参构造必须显示定义(因为有时候实例化一个对象是没有给参数)
public Person(){
}
public Person(String name){
this.name = name;
}
/*
构造器
1、和类名相同
2、没有返回类型
构造器作用
1、new本质在调用构造器(构造方法)
2、初始化对象的值
注意点
定义了有参构造,必须显示定义无参构造
*/
//this.代表当前类的
//IDEA软件快捷键添加构造器 alt+insert
}
package com.jiemyx.oop.demo02;
//一个项目应该只存在一个main方法
public class Application {
public static void main(String[] args) {
//new 实例化了一个对象
Person person = new Person();
System.out.println(person.name);
//实例化一个对象,有参数的
Person person1 = new Person("xiaohua");
System.out.println(person1.name);
}
}
运行结果:
null
xiaohua
原文:https://www.cnblogs.com/Jiemyx/p/14642046.html