hello, i m unable to compile this program. Its giving me compilation error when i am calling am method getName() of subclass. when i wrote the same method in the super class its not giving me an error. why? Is it mandatory to have a method in super class, if i m calling the method of subclass using the polymorphism concept? class A { void display() { System.out.println("Iam display() of A"); }
} class B extends A { private String name; B(String name) { this.name = name; } String getName() { return name; } void display() { System.out.println("Iam display() of B"); } public static void main(String[] args) { A a = new B("Alice"); a.display(); a.getName(); } }
If you assign a reference of type B to your variable a of type A your variable a will behave only like an object of class A. In order to use variable a like an object of class B you have to cast it:
Originally posted by awad saleh: ...Is it mandatory to have a method in super class, if i m calling the method of subclass using the polymorphism concept? ...
Yes. Only the methods in the upcast type will be "exposed" for use. And when you call these methods, the behavior of the subtype will be exhibited.
As Marco suggested, you could downcast the reference back to its original type, but then you wouldn't be using polymorphism.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.