This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes polymorphism n overridng Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "polymorphism n overridng" Watch "polymorphism n overridng" New topic
Author

polymorphism n overridng

awad saleh
Greenhorn

Joined: Jul 04, 2007
Posts: 22
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

Joined: Mar 07, 2007
Posts: 1280

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

Joined: Aug 31, 2004
Posts: 11343

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
 
Don't get me started about those stupid light bulbs.
 
subject: polymorphism n overridng
 
Similar Threads
Casting subclass to superclass type
Method overriding
I am really confused regarding overriding
basic java question...please advice
method overloading issues