public class Wolf extends Animal{
private String name;
private double weight;
public Wolf(String name, double weight) {
this.name = name;
this.weight = weight;
}
public String getDesc() {
return "Wolf[name="+name+",weight="+weight+"]";
}
public static void main(String[] args) {
Wolf wolf=new Wolf("灰太狼", 34);
System.out.println(wolf.name);//灰太狼
System.out.println(wolf);//null
}
}
class Animal{
private String desc; public String getDesc(){
return "This is Animal";
}
public String toString(){
return desc;
}
}
第一个地方不用说了。为什么已经打印出了“灰太狼”,还会打印出null?请赐教!继承,面向对象

解决方案 »

  1.   

    打印对像的引用,就是相当于打印对像的toString方法。Wolf继承Animal,会调用Animal的toString方法,你父类toString方法返回值desc没有初始化,所有为null
      

  2.   

    System.out.println(wolf);//null
    ==调用System.out.println(wolf.toString());//
    而你的
    public String toString(){
    return desc;
    }
    desc没有初始化,当然null
      

  3.   

    你改成wolf.getDesc()就会出现你想要的结果了
      

  4.   

    +1  正确。子类中没有重写toString,所以会调用Animal中的toString。所以返回的是Animal中的desc,所以是null。
      

  5.   

    System.out.println(wolf)  相当于System.out.println(wolf.toString())   输出desc
       而wolf的desc没有初始化