• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Access overwritten method of parent class

 
Peter Irmstadt
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
shivendra tripathi
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Peter,

Can you tell me how we can achive this using reflection ?
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65120
91
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A better way to achieve it it is with proper class design.
 
shivendra tripathi
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone help with source code to achieve the scenario mentioned in thread using reflection.
 
Rob Spoor
Sheriff
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
joseph guse
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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



 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic