利用构造方法为成员变量赋值
public class Person {
private String name;
private int age;
public Person(String name, int age){
this.name = name;
this.age = age;
System.out.println(name+" "+age);
}
}
public class Test {
public static void main(String[] args) {
Person p =new Person("小暖壶",27);
}
}
构造方法的重载:
package day12;
public class Person {
private String name;
private int age;
//构造方法的重载
public Person(String name, int age){
this.name = name;
this.age = age;
}
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;
}
}
建对象
package day12;
public class Test {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.getName());
System.out.println(person.getAge());
person.setName("xiaoqiang");
person.setAge(27);
System.out.println(person.getName());
System.out.println(person.getAge());
Person person2 = new Person("xiaonuanhu",27);
System.out.println(person2.getName());
System.out.println(person2.getAge());
}
}
运行结果:
null
0
xiaoqiang
27
xiaonuanhu
27
修饰权限
构造方法***可以用private修饰***,但只能本类使用,其他类不能new
构造方法和普通方法的区别:
1.定义:构造方法有固定格式,名字和类名一样,不需要返回值
2.运行:构造方法在new时执行,只执行一次,普通方法在调用时运行,可多次运行。
用this.实现构造方法之间的调用:
package day12;
public class Person {
private String name;
private int age;
//构造方法的重载
public Person(String name, int age){
this.name = name;
this.age = age;
}
public Person(){
this("xiaonuanhu", 27);
}
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;
}
}
测试类:
package day12;
public class Test {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.getName());
System.out.println(person.getAge());
}
}
运行结果:
xiaonuanhu
27