Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Calling Supermost class's method with sub most's class reference

 
Deepak Sahu
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Can anyone give the solution for this scenario.

class A
{
public void go()
{
System.out.println("Inside A");
}
}

class B extends A
{
public void go()
{
System.out.println("Inside B");
}
}

class C extends B
{
public void go()
{
System.out.println("InsideC");
}


public static void main(String args[])
{
C c1= new C();




}
}

The requirement is how do we call go() of class A with the reference of C


 
Stefan Evans
Bartender
Posts: 1691
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not able to do this.
You can only call your immediate super class in the hierarchy. No 'skipping' of generations is allowed.

So my solution if you don't want C to invoke B's copy of the method would be to have C extend A directly, rather than B.



 
Stephan van Hulst
Bartender
Pie
Posts: 5590
55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stefan Evans wrote:Not able to do this.
You can only call your immediate super class in the hierarchy. No 'skipping' of generations is allowed.

So my solution if you don't want C to invoke B's copy of the method would be to have C extend A directly, rather than B.


If you think about it, not even this. From a client point of view, there's no way to call B's method through a reference to a C instance. And making a subclass just to call super is rather pointless.

To the original poster: There's no way to do this. It defeats the concept of polymorphism. Why do you want to do this?
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12098
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, please use the 'code' tags when posting java code. you can click the little buttons above where you enter your post to have them drop in, then paste your source between. This will preserver your formatting, making the code much easier to read.

I was going to edit your post to put them in, but found you don't have your code properly formatted. so, my next suggestion would be to ask you to please properly format your code, to make it easier to read.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic