Search code examples
javainheritanceencapsulationinformation-hiding

Do Subclasses Inherit Private Instance Variables From Superclasses


Do subclasses inherit private fields?

This question addresses the same problem but I don't quite understand how that satisfies the (seemingly) contradictory situations below.

http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

Says that "A subclass does not inherit the private members of its parent class."

This means that it neither inherits private instance variables nor private methods right?

However, how does this work if it inherits a public accessor method from its parent? It returns an instance variable that it doesn't know exists?

Also, my computer science book (Baron's AP Computer Science A) has the correct answer to a question that says that "The (Subclass) inherits all the private instance variables and public accessor methods from the (Superclass)."

Isn't this in contraction to oracle's tutorial?

Thanks for your help


Solution

  • Private members are inherited too. To test this, you can do the following in the superclass:

    //...
    private String myText = "I'm in the superclass";
    
    private void setMyText(String myTextValue)
    {
        this.myText = myTextValue;
    }
    
    public void setMyTextPublic(String myTextValue)
    {
        setMyText(myTextValue);
    }
    
    public String getMyText()
    {
        return myText;
    }
    //...
    

    Create a method in the inherited class:

    //...
    public void setMyTextInTheSuperClass(String myTextValue)
    {
        System.out.println(getMyText());
        setMyTextPublic(myTextValue);
        System.out.println(getMyText());
    }
    
    public void setConstantValueToMyText()
    {
        setMyTextInTheSuperClass("I am in the child class");
    }
    //...
    

    And call setConstantValueToMyText somewhere.