public class TestConstructor {
public static void main(String[] args) {
//每次new对象时,都会自动触发对应类的构造方法
//每一个类都会默认存在一个无参的构造方法
Person p = new Person();
System.out.println(p.getAddress());
System.out.println(p.getAge());
System.out.println(p.getName());
//在每次创建对象时,都会执行构造方法
//构造方法的作用:用来创建对象
Person p2 = new Person("张三",18,"白宫");
System.out.println(p2.getAddress());
System.out.println(p2.getAge());
System.out.println(p2.getName());
}
}
//创建Person类。,用来描述任这一类事物
class Person{
private String name;
private int age;
private String address;
//构造方法--有参
public Person(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
//构造方法--无参
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public void eat(){
System.out.println("干饭不积极,脑子有问题");
}
}
|