This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Java in General and the fly likes multi-level inheritance problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "multi-level inheritance problem" Watch "multi-level inheritance problem" New topic
Author

multi-level inheritance problem

sudhakar pinjala
Greenhorn

Joined: Apr 21, 2003
Posts: 1
Hi all
I have a problem here...Let me explain it as simple as possible.
class A{
public void met1(){
System.out.println("A--> met1 is called");
}
}
class B extends A {
public void met1(){
System.out.println("B--> met1 is called");
}
}
class C extends B {
public void met1(){
System.out.println("C--> met1 is called");
}
public void test(){
/* Now my question is , Here i need to call the method of class A with a reference of C. How can i do that? Is it possible?
*/

}

}

Prompt response will be appreciated. Alternatively, u can mail me at sudhakar390@indiatimes.com
Francis Siu
Ranch Hand

Joined: Jan 04, 2003
Posts: 867
hi sudhakar
Welcome


/* Now my question is , Here i need to call the method of class A with a reference of C. How can i do that? Is it possible?
*/

It is impossible that the class C method overrides the class A method met1()
If you want to use the same method name, you must use the class A reference and do the type casting from class C to class A.
I hope that I can answer your question


Francis Siu
SCJP, MCDBA
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1821

This turned out to be a longer post than I intended......
Typecasting will not solve this little problem. No matter what you do, you cannot call A's met1 from outside the class. And even inside the class this becomes a little bit interesting, since the desired method is in a grandparent class.
The only way around this would to write a method like by adding some methods to the classes:

The reason for this is simple: Your objects are overriding their super class's methods for some reason. As such code outside the class does not have the choice of what mthod to call. Think of it this way:

Now, if you have a DuckBilledPlatypus instance, there should be no way to call the generic Mammal's giveBirth() method; DuckBilledPlatypuses (DuckBilledPlatypii??) just don't do that.


Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: multi-level inheritance problem