Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Code call (Inheritance)

 
Wu Wen
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The question is How can you let perform_work() method of A to be called from an instance method in C?
And the right answer is There is no way to go more than one level up for methods.

I thought I could use ( (A) this ).perform_work( ) in C to call A's perform_work(), but I got StackOverflowError.
Can anyone explains me why it is not working?

Thanks
 
Tomasz Sochanski
Ranch Hand
Posts: 47
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wu Wen wrote:
I thought I could use ( (A) this ).perform_work( ) in C to call A's perform_work(), but I got StackOverflowError.
Can anyone explains me why it is not working?


Wu - please provide your code here, there are no exceptions runnig ie. this code:

 
Wu Wen
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here it is
 
Matthew Brown
Bartender
Posts: 4567
8
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't do what you're trying to do. You can cast to a superclass, but polymorphism means that you'll still be calling the version of perform_work() in the subclass. Which means that in your code the method is calling itself, which leads to a stack overflow.

The only way to call the superclass method is via super.perform_work(), but that only calls the version in the immediate superclass.
 
Wu Wen
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:You can't do what you're trying to do. You can cast to a superclass, but polymorphism means that you'll still be calling the version of perform_work() in the subclass. Which means that in your code the method is calling itself, which leads to a stack overflow.

The only way to call the superclass method is via super.perform_work(), but that only calls the version in the immediate superclass.


I get it. Thank you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic