obj.f(): Call f( ) in class Z, call f( ) in class parent and output 3
obj.g(): Call g( ) of class Z and output 4
Output result: 34
I solved it in the same format as above, and the answer was 32.
The answer is 32. If you run the code as it is, "3" + "2" will be printed.
Xobj = newZ(),
obj is assigned an instance of the upcasting
Z class as
And the methods of
Y are 'covered' due to upcasting.
Y.f() is hidden, so you might think that you cannot call. However, in this inheritance,
X.f() only serves to guide
Y.f() (so that it can be called). The actual invocation is
Y.f() that overrides
X.f(). (If you ask why this is happening...) Java is just like that 🤭)
So the actual output is
"3" and this is what happens when you fix the code:
For example, if you have this class:
Let's upcast with
Object which is a super class of all classes:
obj2.toString() points to
Object.toString() but what actually runs is
Static methods are excluded from inheritance. In addition,
X.g() is a static method and must be called static. Therefore, calling through the instance is the wrong way, as shown below:
However, since Java corrects it, there is no error. Because it automatically changes like below:
I am attaching another example below:
I'm not sure what dynamic binding means. 🤔
© 2022 pinfo. All rights reserved.