Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

polymorphism n overridng

 
awad saleh
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
}
}
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!


A a = new B("Alice");


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:

((B) a).getName() should work!
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic