Is it possible to call subclasses' methods on a superclass object?

roberto picture roberto · May 22, 2009 · Viewed 48.8k times · Source

Animal is a superclass of Dog and Dog has a method called bark

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

Consider the following:

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

What will happen?

  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

I said 2 as we are checking if the object is a dog; as dog is the class with the bark method in it, if it is then we call it which will print out :s

Is my understanding correct here?

Answer

Sam Trost picture Sam Trost · May 22, 2009

This won't compile since Animal does not have a method called bark. Think of it this way, all dogs are animals, but not all animals are dogs. All dogs bark, but not all animals bark.