File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Spring in Action this week in the Spring 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: 1282

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: polymorphism n overridng