Java-面向对象_构造器的重载
类:
public class Person1 { String name; int age; double height; public Person1() { } //构造器的重载 public Person1(String name,int age,double height) { //当形参名字和属性名字重名的时候,会出现就近原则; //当要表示对象的属性前加上this.来修饰,因此this代表的就是你创建的那个对象 this.name= name; this.age = age; this.height = height; } public Person1(String a,int b) { name = a; age = b; } }
对象:
Person1 p1 = new Person1("小明", 18); System.out.println(p1.name); System.out.println(p1.age); System.out.println(); Person1 p2 = new Person1("小李", 19, 170.5); System.out.println(p2.name); System.out.println(p2.age); System.out.println(p2.height);
运行: