public class Demo { public static void main(String[] args) { Son s1 = new Son(); // 子类空参构造方法,优先输出父类空参构造方法 System.out.println(s1.getName()+"..."+ s1.getAge()); System.out.println( "******************
public class Demo { public static void main(String[] args) { Son s1 = new Son();//子类空参构造方法,优先输出父类空参构造方法 System.out.println(s1.getName()+"..."+s1.getAge()); System.out.println("***********************************"); Son s2 = new Son("张三",23);//先访问父类有参构造方法,再访问子类 //打印张三 23 System.out.println(s2.getName()+"..."+s2.getAge()); } } class Father { private String name;//name 和 age 都设为私有,子类只能 super 访问 private int age; 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 Father() { System.out.println("父类的空参构造方法"); }
public Father(String name,int age) {
this.name=name;
this.age=age;
System.out.println("父类的有参构造方法");
}
}
class Son extends Father {
public Son() {
//系统会默认添加第一条语句 super();调用父类空参构造方法
System.out.println("子类的空参构造方法");
}
public Son(String name,int age) {
super(name,age);//访问父类
System.out.println("子类的有参构造方法");
}
}
打印结果: