JJJ
JJJ

Reputation: 19

Java - Problems with understanding inheritance

I am facing some problems about inheritance in Java. I can't understand why the following two programs have those outputs! Could anyone help me? :)

1)

public class A {
    int foo() {
        return 1;
    }
}

public class B extends A {
    int foo() {
        return 2;
    }
}

public class C extends B {
    int bar(A a) {
        return a.foo();
    }
}

C x = new C();  
System.out.println(x.bar(x));

// OUTPUT:2

2)

public class A {
    int e=1;
}

public class B extends A {
    int e=2;
}

public class C extends B {
    int bar(A a){
        return a.e;
    }
}

C x= new C();
System.out.println(x.bar(x));

// OUTPUT:1

Upvotes: 0

Views: 117

Answers (1)

Jake Fairbairn
Jake Fairbairn

Reputation: 223

In both cases, you're passing in an object of type C into the print function. The bar function asks for an object of type A, but it's still acceptable for you to pass in an object of type C since it is a subclass of A. So first of all, it's important to keep in mind that a.foo() and a.e are being called on a C object.

So what is happening in both cases is that it's searching for the lowest attribute or method in the list. Here is a very simplified version of what Java is doing in part 1:

  1. Hey, you've passed in an object of type C to the bar method! Now let's call its foo method.
  2. Whoops! C doesn't have a foo method! Let's take the next step up to the B class to see if it has a foo method.
  3. Yay! B has a foo method, so let's call it. No need to work our way up to the A class because we've already found what we need in B.

It's all about understanding that the parameter was downcast from A to C. The exact same sort of logic is used in part 2. It notices that an object of type C was passed in, so it gets the e attribute from object B since its the lowest class in the hierarchy that contains that attribute.

Hopefully that answers your question!

Upvotes: 1

Related Questions