| Author |
Access overwritten method of parent class
|
Peter Irmstadt
Greenhorn
Joined: Mar 01, 2009
Posts: 24
|
|
Hi!
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: 1295
|
|
|
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
Marshal
Joined: Jan 10, 2002
Posts: 56232
|
|
|
A better way to achieve it it is with proper class design.
|
[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About 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
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
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:
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
joseph guse
Greenhorn
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
|
 |
 |
|
|
subject: Access overwritten method of parent class
|
|
|