In: Computer Science
Given the following Java code:
class C { public int foo(C p) { return 1; } } class D extends C { public int foo(C p) { return 2; } public int foo(D p) { return 3; } } C p = new C(); C q = new D(); D r = new D(); int i = p.foo(r); int j = q.foo(q); int k = q.foo(r);
(Remember that in Java every object is accessed through a pointer and that methods are virtual by default.)
Which methods get called in the three calls, i.e., what are the values of i, j, and k? Explain how the method selection works to result in these values.
For this statement, C p = new C(); , p object is created for class C as we have directly declared it.
Now for the second statement i.e., C q = new D(); ,since D is extending properties of C using inheritance, the object is created for class D i.e., q points to class D but of type class C.
Now in the similar way, the third statement i.e., D r = new D(); , here also the object is directly created to class D itself.
Now to compute i value in statement int i = p.foo(r); => p is object of class C and hence foo() in class C i.e.,
public int foo(C p) { return 1; } gets invoked and value of 1 is returned.
Now to compute j value in statement int j=q.foo(q); => q is object of class D but type of class C and hence foo() in class D i.e.,
public int foo(C p) { return 2; } gets invoked and value of 2 is returned.
Now to compute k value in statement int k=q.foo(r); => q is object of class D but type of class C and r is object of class D and hence foo() in class D i.e.,
public int foo(C p) { return 2; } gets invoked and value of 2 is returned.
This is happening because of method overriding.
So the output will be
i=1
j=2
k=2