| Author |
Inheritance concepts
|
Thirumurugan Mylrajan
Ranch Hand
Joined: Jan 26, 2006
Posts: 64
|
|
Can somone please explain the Inheritance concepts in the following code. What values are printed and how the Compiler chooses the values and methods to be executed. What if the base instance-variable/method is static and the Derived variable/method is static.
|
SCJP , SCJD. (IBM 142 in progress).
|
 |
Sridhar Sreenivasan
Greenhorn
Joined: Dec 08, 2005
Posts: 10
|
|
Hi, With the existing code it will print derived x is 2 test x is 3. This is a case of overriding.During overriding the method is resolved at runtime by the object.In this case the object instance is Dervied though the variable is Base. So it will invoke the show of the Dervied. But this applies only to methods and not to variables.So the test x is 3 will be printed from the Base. As for making it static it is a case of shadowing,thereby it will print base x is 3 test x is 3 That is pretty straight forward as no overriding is applied.So during compile time the reference variable method will be applied.Hope this helped. Sridhar.
|
 |
Thirumurugan Mylrajan
Ranch Hand
Joined: Jan 26, 2006
Posts: 64
|
|
Thanks for the clarification. I made a mess with the code(constructors, case).. What will happen if we do the following. Base b = new Derived(); b.show(); Base c = (Base)b; c.show(); Why Does Casting have no effect?.
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24057
|
|
Hi, Welcome to JavaRanch! First, a bit of business: you may not have read our naming policy on the way in. It requires that you use a full, real (sounding) first and last name for your display name. Initials aren't enough for a last name. You can change your display name here. Thanks! Now as to your question: a cast never changes an actual object. A cast is just a way of telling the compiler about the type of an object. In your example code, the cast is redundant -- i.e., you're telling the compiler something it already knows, and the code would compile without it. In the below, however, the cast is required -- but you still get the same answer: Base b = new Derived(); Derived d = (Derived) b; d.show(); No matter what you do, any time you call show() on that Derived object you create, the subclass's version of show() will be called. There is absolutely nothing you can do (without changing the code in Derived) to change the result of calling d.show(). You can cast it to anything you like, assign it to variables of any kind, and nothing will ever change the result.
|
[Jess in Action][AskingGoodQuestions]
|
 |
 |
|
|
subject: Inheritance concepts
|
|
|