Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloading and Overriding

 
Sukesh Jain
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Can you please tell me what would be the outcome of the below program and the reason behind such outcome?

Thanks & Regards,
Sukesh.

 
Ankit Garg
Sheriff
Posts: 9510
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sukesh, welcome to javaranch

Sukesh please Use Code Tags when you post a source code. That way your code looks formatted. Unformatted code is hard to read. You can add code tags by wrapping your code in [code] [/code] tags. You can edit your message using button and then add code tags to it...
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The YourKnowledgeTest.test() is private so YourExtensiveKnowledgeTest.test() is not overriding it. It is simply creating a method with the same name. Since your main() method is part of YourKnowledgeTest, you have access to the private method. Because you are assigning a reference to the YourExtensiveKnowledgeTest instance in a YourKnowledgeTest variable, the compiler only sees YourExtensiveKnowledgeTest as a YourKnowledgeTest and therefore calls the only test() method it knows about (the private one).

Note that had you moved the main() method to YourKnowledgeTest then you would have gotten a compiler error because the compiler does not have access to the private method test().
 
Sukesh Jain
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Tom,

Thanks for the explanation.

I thought the invocation of method is determined at runtime and not at compilation time. In this case, either it should result in runtime error as there is no overriding test method.

Thanks & Regards,
Sukesh.

PS @Ankit: Thanks for the code tag information.
 
Michael Angstadt
Ranch Hand
Posts: 277
Eclipse IDE Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sukesh Jain wrote:I thought the invocation of method is determined at runtime and not at compilation time. In this case, either it should result in runtime error as there is no overriding test method.


There's no error here. YourKnowledgeTest.test() is private, so YourExtensiveKnowledgeTest.test() does not override it. This means that when you call test.test() in your code, it calls YourKnowledgeTest.test().
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic