Java 是否可以对超类对象调用子类的方法?

 

问题描述:

动物是狗的超类,狗有一种叫bark的方法

public void bark()
{
    System.out.println("woof");
}

考虑以下:

Animal a = new Dog();
if (a instanceof Dog){
    a.bark();
}

会发生什么?

  1. the assignment isn’t allowed
  2. the call to bark is allowed and “woof” is printed at run time
  3. the call to bark is allowed but nothing is printed
  4. the call to bark causes a compile time error
  5. the call to bark results in a run time error

我说2是因为我们正在检查物体是否是狗;因为dog是其中包含bark方法的类,如果是,则将其调用,它将打印出:s

我的理解对吗?


 

第 1 个答案:

因为Animal没有名为bark的方法。这样想吧,所有的狗都是动物,但不是所有的动物都是狗。所有的狗都会叫,但不是所有的动物都会叫。


这不会编译,以下方法只会写出我添加的最新项目,而不会追加到以前的条目中。我究竟做错了什么?public void addNew() { try { PrintWriter pw = n ...