这个问题是关于java中常见的继承问题,动物作为父类,狼作为子类,灰太狼作为狼的对象
问题代码如下:
class Animal {
private String desc ;
public Animal(){
this.desc = getDesc() ;
}
public String getDesc(){
return "Animal" ;
}
public String toString(){
return desc ;
}
}
public class liu extends Animal {
private String name ;
private double weight ;
public liu(String name , double weight){
this.name = name ;
this.weight = weight ;
System.out.println("1"+name);//测试语句1
}
public String getDesc(){
System.out.println("2"+name);//测试语句2
return "Wolf[name=" + name + ",weight=" + weight + "]" ;
}
public static void main(String[] args){
liu k=new liu("灰太狼" , 3);
System.out.println(k);
}
}
让小弟困惑的是程序执行的时候,为什么要先执行语句2,而不是1?麻烦各位了,如果能顺便分享一点经验给小弟关于学习java的类的,小弟感激不尽。因为刚来,没有积分,还望各位见谅。
问题代码如下:
class Animal {
private String desc ;
public Animal(){
this.desc = getDesc() ;
}
public String getDesc(){
return "Animal" ;
}
public String toString(){
return desc ;
}
}
public class liu extends Animal {
private String name ;
private double weight ;
public liu(String name , double weight){
this.name = name ;
this.weight = weight ;
System.out.println("1"+name);//测试语句1
}
public String getDesc(){
System.out.println("2"+name);//测试语句2
return "Wolf[name=" + name + ",weight=" + weight + "]" ;
}
public static void main(String[] args){
liu k=new liu("灰太狼" , 3);
System.out.println(k);
}
}
让小弟困惑的是程序执行的时候,为什么要先执行语句2,而不是1?麻烦各位了,如果能顺便分享一点经验给小弟关于学习java的类的,小弟感激不尽。因为刚来,没有积分,还望各位见谅。
liu k=new liu("灰太狼" , 3);
这句话会调用构造函数
public liu(String name , double weight){
而根据构造函数规范,会预先调用父类构造函数(递归直到Object类)
public Animal(){
父类构造函数先执行了
this.desc = getDesc();
但getDesc()这个函数实际上被子类liu所重写了(overwrite)
public String getDesc(){
System.out.println("2"+name);//测试语句2
return "Wolf[name=" + name + ",weight=" + weight + "]" ;
}
父类构造函数执行完毕后,才会开始执行子类构造函数的其余代码。
大致理解么?