Banupriya
Banupriya

Reputation: 195

Polymorphic behavior in java

I have following java code,

interface A {
    int a = 5;
}

class B {
    int a = 6;
}

public class C extends B implements A {
    int b = super.a;//Line 10
    public static void main(String[] a) {
        System.out.println(new C().b);//6

    }
}

I was expecting compiler error at line 10 because compiler will not know which "a" to refer. But there was no compiler error. Output is 6. Can someone explain how it takes class B 's instance variable value(6) why not interface A's "a" value which is 5?.

Upvotes: 1

Views: 61

Answers (1)

Ashishkumar Singh
Ashishkumar Singh

Reputation: 3600

super keyword is used to refer to the parent class which in this case is B. Hence you get output as 6.

a defined in interface A is static and a defined in Class B is an instance variable. Hence when we do super.a, it refers to the instance value of a which is defined in the Class B

If you rename the variable in B say as aa, you will get compiler error saying a cannot be resolved or is not a field because a defined in interface A is not directly accessible in class C, because it is by default static. To access a defined in interface A, we need to make an explicit call to A.a in class C

If you define, a as static in class B, and remove super, you will get compiler error: The field a is ambiguous

Upvotes: 2

Related Questions