• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

Java Puzzle #7: Inheritance and Visibility

Contents

  • Java Puzzle #7: Inheritance and Visibility
    • Answer

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)

Published

Aug 5, 2012
by Martin Thoma

Category

Code

Tags

  • Java 36
  • Programming 52
  • puzzle 22

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor