Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

multi-level inheritance problem

 
sudhakar pinjala
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 867
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic