O'Reilly logo

Java™ Puzzlers: Traps, Pitfalls, and Corner Cases by Neal Gafter, Joshua Bloch

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8. Classier Puzzlers

The puzzles in this chapter concern inheritance, overriding, and other forms of name reuse.

Puzzle 66: A Private Matter

In this program, a subclass field has the same name as a superclass field. What does the program print?

class Base {    public String className = "Base";}class Derived extends Base {    private String className = "Derived";}public class PrivateMatter {    public static void main(String[ ] args) {        System.out.println(new Derived( ).className);    }}

Solution 66: A Private Matter

A superficial analysis of the program might suggest that it should print Derived, because that is what is stored in the className field of each Derived instance. A deeper analysis suggests that class Derived won’t ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required