wood burning stoves
The moose likes Java in General and the fly likes Access overwritten method of parent class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Access overwritten method of parent class" Watch "Access overwritten method of parent class" New topic

Access overwritten method of parent class

Peter Irmstadt

Joined: Mar 01, 2009
Posts: 24

I have the following construct:

The first output of the main method of course is 'B'. The second is 'B' as well because A's method getTest has been overwritten by B. Is it anyhow possible to access the overwritten method and get the output 'A' from the object o?
I can't use Reflection for this at all because this will be transfered to an existing problem on the Android platform (but I posted it here because it isn't a pure Android problem).

Is there any way to realize that using 'Standard Java'?

Thank you in advance!
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
No. That is what polymorphism is all about. Basically if you need the behavior of A, then you need an instance of A not an instance of B.

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
shivendra tripathi
Ranch Hand

Joined: Aug 26, 2008
Posts: 263
Hi Peter,

Can you tell me how we can achive this using reflection ?

SCJP 1.5(97%) My Blog
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63873

A better way to achieve it it is with proper class design.

[Asking smart questions] [About Bear] [Books by Bear]
shivendra tripathi
Ranch Hand

Joined: Aug 26, 2008
Posts: 263
Can anyone help with source code to achieve the scenario mentioned in thread using reflection.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20279

You can't. Sure, you can get access to the Method of class A. But if you then call invoke on it, it will still call B's getTest:

How To Ask Questions How To Answer Questions
joseph guse

Joined: Jun 24, 2010
Posts: 1
It should be noted that the subclass CAN access the overwritten method by using the super keyword. Not sure how useful this is to the original questioner, but if you added a method "getTestSuper()" to your B class like so

Now this can be called from you main method

I agree. Here's the link: http://aspose.com/file-tools
subject: Access overwritten method of parent class
It's not a secret anymore!