mmm23545 mmm23545 - 4 months ago 13
Java Question

Why when you call method of parent from a second inheritance is from first inheritance?

I am confused:

I run this example and the results is 2.

I can't find any explication:

  • so we have an F object. This is called
    here and a copy of an F object is sent to fun method.

  • here we have
    fun(D d)
    where we will have a copy of x but in a D object.

  • d.method() is clearly calling for me D method which return 1;

However the result is 2...what i am wrong?

import java.util.*;
import java.lang.*;

class D {int method() {return 1;}}
class E extends D {
int method() {
return 2;

class F extends E {
int fun(D d){
return d.method();

/* Name of the class has to be "Main" only if the class is public. */
class Test2 {
public static void main (String[] args) {
F x = new F();

  • The d.method() method call executes the method that fits the runtime type of d.

  • In your case, the runtime type of d is F (since you create in your main an instance of F and pass it to the fun() method).

  • F extends E, and E overrides method(). Therefore d.method() calls E's implementation of method(), which returns 2.