Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Access overwritten method of parent class" Watch "Access overwritten method of parent class" New topic
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: 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
Marshal

Joined: Jan 10, 2002
Posts: 60800
    
  65

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


[Asking smart questions] [Bear's FrontMan] [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
Sheriff

Joined: Oct 27, 2005
Posts: 19655
    
  18

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 - OCEEJBD 6
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



 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Access overwritten method of parent class
 
Similar Threads
asking about interfaces
Abstract class method
Polymorphism Question
Overriden Vs Re-Define
javabeat generics question doubt