This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
You need to check up on inheritance, polymorphism and instance methods. In brief, although you are invoking the doStuff() method on an object reference of type A, at runtime the JVM knows that the actual type of the instantiated object is B, and it invokes B's version of the method.
This feature applies to instance methods which can be overridden (as here) and not to static methods or variables (which is why your code prints the value of A's x variable).
I'm sure others can provide fuller explanations...
Joined: Jun 25, 2012
Thanks for the responses.
And let me rephrase my question,
I am basically asking if I can access the super class' overridden method by using a subclass object.
So in the link provided above, the Dog class has its own play() method that overrides the Animal's play() method (Dog extends Animal) What if i wanted a Dog to "play" like an Animal instead? Is that possible?
By using super, A.doStuff() will always be called when B.doStuff() is called.
I am trying to call A.doStuff() instead of B.doStuff() by using a B object in another class (such as C).
This might not make sense because it is illegal? Im not sure!
So, as I am "overriding" the integer variable x by casting an A object :
I wanna know if I can access overridden methods of the super class in a similar fashion.
I was expecting the following to accomplish this but it doesnt:
There is a huge difference between variables and methods: methods can be overridden, variables can't (although it looks like it, but a variable in a subclass is just shadowing a variable with the exact same name in the parent class.
That's why in your example ((A)b).x will print 15 (no overriding, A and B just have a variable with the same name), but with method doStuff you have overriding and thus polymorphism. If you have an instance of type B, it will always run the doStuff-method of class B. Casting to A won't help, because which (overridden) method to execute is decided at runtime and at runtime your instance is still from class B (so its method is called).
You can however (like illustrated by Mala) call the method of the parent class by calling super from the method from the child class. Or you can create an instance of class A and invoke its doStuff-method. But creating an
George Panadis wrote:I am trying to call A.doStuff() instead of B.doStuff() by using a B object in another class (such as C).