Java Puzzle #7: Inheritance and Visibility

· by

You are given the following two classes: Animal.java:

public class Animal {
    private final int height = 120;
}

Tiger.java:

public class Tiger extends Animal {
    public int height;
}

What is the output of the following three snippets: test1.java:

public class test1 {
    public static void main(String[] args) {
        Tiger t = new Tiger();
        System.out.println(t.height);
    }
}

test2.java:

public class test2 {
    public static void main(String[] args) {
        Animal t = new Tiger();
        System.out.println(t.height);
    }
}

test3.java:

public class test3 {
    public static void main(String[] args) {
        Animal t = new Animal();
        System.out.println(t.height);
    }
}

. . . . . . . . . . . . . . . . . . . . . . . . . .

Answer

test1.java:

0

test2.java:

Exception in thread "main" java.lang.Error: Unresolved compilation
      problem:
    The field Animal.height is not visible

    at test.main(test.java:4)

test3.java:

Exception in thread "main" java.lang.Error: Unresolved compilation
      problem:
    The field Animal.height is not visible

    at test.main(test.java:4)