Kevin Lowe Kevin Lowe - 5 months ago 13
Java Question

Inheritance and static type java

I was playing around with classes since I'm learning java syntax and I came across this weird situation. So given a class

A
and
B
:

public class A {
public int x() {
return x;
}
}

public class B extends A {
int x = 5;
public int x() {
return x + 2;
}
public static void main(String[] args) {
B b = new B();
System.out.println(b.x());
}


When I execute the main method I get a compile time error that it doesn't find the
x
variable and it's calling the method from
A
because the error shows
return x
instead of
return x + 2
. Since
b
's static type is
B
, why is it looking in
A
for
x
?

error: cannot find symbol

return x;

symbol: variable x
location: class A

Answer

The class A doesn't know that it will be extended by B, where the x variable will exist.

In order to make this compile, make A.x() abstract and provide implementation within the subclass:

public abstract class A {
     public abstract int x();
}

public class B extends A {
    int x = 5;

    @Override
    public int x() {
        return x + 2;
    }
..
}