| Author |
Overloading and Overriding
|
Sukesh Jain
Greenhorn
Joined: Jun 27, 2010
Posts: 3
|
|
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
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9189
|
|
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...
|
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
|
 |
Tom Reilly
Rancher
Joined: Jun 01, 2010
Posts: 618
|
|
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
Joined: Jun 27, 2010
Posts: 3
|
|
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
Joined: Jun 17, 2009
Posts: 272
|
|
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().
|
SCJP 6 || SCWCD 5
|
 |
 |
|
|
subject: Overloading and Overriding
|
|
|