0
class Testing{

public static void main(String[] args)  {

    Animal d = new Dog();
    /*This is totally legal, calling
    the method run is no problem 
    because it is defined inside 
    the Animal class: */
    d.run();

    /*Compliler Error! Calling
    the method bark results
    in an error because it is
    not defined in the Animal
    class:  */
    d.bark();

}

}

My Question is:

  1. Why subclass method cannot be called when it has super class refernce? How it internally stored?
  2. Usually super class refernce is used to point the sub class objects, If we cant call subclass specific methods, then where its prefered to have super class refernce to sub class object, i means whats the scenario?
javac
  • 2,431
  • 4
  • 17
  • 26
ashu
  • 579
  • 2
  • 6
  • 17
  • 7
    Your answer can be found here: http://stackoverflow.com/questions/898909/is-it-possible-to-call-subclasses-methods-on-a-superclass-object – Taylor Caldwell Sep 08 '15 at 08:22
  • 1
    d is an Animal and an Animal cannot bark. Therefor d cannot bark. Or in Java terms, d.bark() won't compile. – Manu Sep 10 '15 at 13:03

0 Answers0