Reputation: 9478
class BaseClass {
int data = 101;
public void print() {
System.out.print(data + " ");
}
public void fun() {
print();
}
}
class SubClass extends BaseClass {
int data = 202;
public void print() {
System.out.print(data + " ");
}
}
class TestClass {
public static void main(String[] args) {
BaseClass obj = new SubClass();
obj.print();//call 1
obj.fun();// call 2
System.out.print(obj.data);//call2
}
}
So I have a parent/child relation class and one test class which has call1, call2, call3.
1:Regarding call1 , My reasoning was that since print() is being overridden by the child class and the function call will print the data variable of the correct. This appears to be correct since that is what the correct answer is.
2: Now regarding call2, since fun is present only in the parent class, so the call will go there and ideally should call the fun method of the parent class and output the data variable of the parent class. This is not the correct answer, according to the answer it the output data of the child class.
Can anyone explain to me, what is wrong with my reasoning?
Upvotes: 0
Views: 101
Reputation: 8473
case 1 : obj.fun();
You have overridden the print();
method .
At runtime java resolves method calling based on the object type.
So here it searches for method fun()
first in SubClass
,it not found the method there,
since you SubClass
do not have it(you are not overrridden fun()
there),and
then it go for BaseClass
(parent) class and found there the fun()
method.
Then there is a method print()
it has to executes.
Here also it follows the same procedure here,searches first in SubClass
and found the print()
in the SubClass
itself and executes it.
So that is whay you are getting the result like that.
case 2 : System.out.println(obj.data)
Here data
is variable ,
The compiler only considers the declared type of variables when resolving access to variables(and also when resolving overloading)
Here declared type is BaseClass
,So result is 101
.
If you create object like this
SubClass obj2 = new SubClass();
System.out.println(obj2.data);
Then result will be 202
.Since declared type is 'SubClass'.
Upvotes: 1
Reputation: 4211
This is due to polymorphism. You override the print()
method in the child so that when the instance of child calls fun()
it calls it's using the SubClass version of the print()
method.
As the instance is SubClass it will use the version of the method it has and not its parent.
A good resource on how the JVM resolves its methods can be found here
Upvotes: 4
Reputation: 17622
Now regarding call2, since fun is present only in the parent class, so the call will go there and ideally should call the fun method of the parent class and output the data variable of the parent class. This is not the correct answer, according to the answer it the output data of the child class.
This is not correct. fun()
of BaseClass
will call print()
of Subclass
because its overriden. Runtime polymorphism applies here.
Upvotes: 1