class ZiLeiGouZaoFangFaDouHuiFangWenFuLeiGouZao {
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);
System.out.println(s2.getName()+" "+s2.getAge());
}
}
class Father {
private String name;
private int age;
public Father(String name,int age){
this.name = name;
this.age =age;
System.out.println("父类的有参构造");
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
}
class Son extends Father {
public Son(){
super("lisi",32);/////////////////////////////////////////
System.out.println("son的空参构造");
}
public Son(String name,int age){
super(name,age);
System.out.println("son的有参构造");
}
}
输出结果为
C:\Users\Administrator\Desktop
再看下面代码
class ZiLeiGouZaoFangFaDouHuiFangWenFuLeiGouZao {
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);
System.out.println(s2.getName()+" "+s2.getAge());
}
}
class Father {
private String name;
private int age;
public Father(String name,int age){
this.name = name;
this.age =age;
System.out.println("父类的有参构造");
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
}
class Son extends Father {
public Son(){
super(name,age);/////////////////////////////////////////
System.out.println("son的空参构造");
}
public Son(String name,int age){
super(name,age);
System.out.println("son的有参构造");
}
}
变异显示错误,为什么子类无参的构造方法不能像子类有参的构造方法那样写成super(name,age)进行调用父类构造方法呢? |
|