父类Person:
package Super;
public class Person {
String name;
int age;
double salary;
double height;
public Person() {
System.out.println("调用父类无参构造器");
}
public Person(String name, int age, double salary) {
System.out.println("调用父类三参构造器");
this.name = name;
this.age = age;
this.salary = salary;
}
public void showInfo() {
System.out.println("name:" + name + " age:" + age + " salary:" + salary + " height:" + height);
}
}
子类Student
package Super;
public class Student extends Person {
public Student() {
}
public Student(String name, int age) {
System.out.println("调用子类二参构造器");
this.name = name;
this.age = age;
salary = 999.99;//调用二参构造器给salary设置默认值
height = 999.99;//调用二参构造器给height设置默认值
}
public Student(String name, int age, double salary) {
this(name, age);//首行有了this()就不会再有默认的super()
System.out.println("调用子类三参构造器");
super.salary = salary;//super可以写this,也可以不写(省略this),最终都是去Person类中找成员变量
this.height = 999.99;//调用三参构造器给height设置默认值,演示使用this找成员变量
}
public Student(String name, int age, double salary, double height1) {
super(name, age, salary);
System.out.println("调用子类四参构造器");
height = height1;//演示省略this找成员变量,由于不用this和super会出现重名问题所以改了形参名为height1
}
}
程序入口:
package Super;
public class DemoStudent {
public static void main(String[] args) {
new Student("李白", 18).showInfo();
System.out.println("==================================================");
new Student("李白", 18, 10000.0).showInfo();
System.out.println("==================================================");
new Student("李白", 18, 10000.0,1.78).showInfo();
}
}
输出结果:
调用父类无参构造器
调用子类二参构造器
name:李白 age:18 salary:999.99 height:999.99
==================================================
调用父类无参构造器
调用子类二参构造器
调用子类三参构造器
name:李白 age:18 salary:10000.0 height:999.99
==================================================
调用父类三参构造器
调用子类四参构造器
name:李白 age:18 salary:10000.0 height:1.78