Private members in Java inheritance

35,660

Solution 1

No, the private member are not inherited because the scope of a private member is only limited to the class in which it is defined. Only the public and protected member are inherited.

From the Java Documentation,

Private Members in a Superclass

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass. A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.

From the JLS,

Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.

A useful link : Does subclasses inherit private fields?

Solution 2

This kind of depends on your exact usage of the word inheritance. I'll explain by example.

Suppose you have two classes: Parent and Child, where Child extends Parent. Also, Parent has a private integer named value.

Now comes the question: does Child inherit the private value? In Java, inheritance is defined in such a way that the answer would be "No". However, in general OOP lingo, there is a slight ambiguity.

You could say that it not inherited, because nowhere can Child refer explicitly to value. I.e. any code like this.value can't be used within Child, nor can obj.value be used from some calling code (obviously).

However, in another sense, you could say that value is inherited. If you consider that every instance of Child is also an instance of Parent, then that object must contain value as defined in Parent. Even if the Child class knows nothing about it, a private member named value still exists within each and every instance of Child. So in this sense, you could say that value is inherited in Child.

So without using the word "inheritance", just remember that child classes don't know about private members defined within parent classes. But also remember that those private members still exist within instances of the child class.

Solution 3

You will be satisfied here 100%. I tested it on my computer and what I concluded I'm going to post it here. Just go through the program written below, see the program output and READ THE CONCLUSION given at the end. To test it yourself, copy the whole program and save it in a file named "InheritanceTest.java" then compile it and finally run it.

Program

// Testing if a subclass can access the private members of a superclass

class Class1 {
    private String name;

    public void setName(String name) {
        this.name = name;
        System.out.println("The name has been set successfully.");
    }

    public void showName() {
        System.out.println("The name is: " + name);
    }
}

class Class2 extends Class1 {
    private int age;

    public void setAge(int age) {
        this.age = age;
        System.out.println("The age has been set successfully.");
    }

    public void showAge() {
        System.out.println("The age is: " + age);
    }

    public void displayName() {
        //Accessing the private member of superclass here
        //System.out.println("The name is: " + name); //error, can't compile because access to the private member name of the superclass Class1 is not permitted here.
    }
}

class InheritanceTest {
    public static void main(String[] args) {

        Class1 c1 = new Class1();
        Class2 c2 = new Class2();

        c1.setName("Name_C1");
        c2.setName("Name_C2"); //No error, setName() is a public member of the superclass which indirectly gives access to the private member "name".

        c1.showName();
        c2.showName(); //No error, showName() is a public member of the superclass which indirectly gives access to the private member "name".

        c2.setAge(25);
        c2.showAge();

        //c2.displayName(); //error
    }
}

Output

The name has been set successfully.
The name has been set successfully.
The name is: Name_C1
The name is: Name_C2
The age has been set successfully.
The age is: 25

Conclusion

Yes, a subclass can indirectly access the private members of a superclass. A subclass can't directly access the private members of a superclass.

All the public, private and protected members (i.e. all the fields and methods) of a superclass are inherited by a subclass but the subclass can directly access only the public and protected members of the superclass. If an inherited member from a superclass gives access to a private member of the superclass then the subclass can use this inherited member to access the private member of the superclass.

Solution 4

IMO by no way is it a matter of definition. In class-based Inheritance implies propagation of behavior to descendants. As such private members DO get inherited , and I will not go into the details how this happens.

Actually I find the "not inherited" answer to be dangerous for new developers and they do not comprehend right away that the private members are there hidden under the skin of your class and they (can) have severe impact on its behavior, size of the objects etc.

It is common that "development comes before understanding" in computer science, however lets avoid building (or destroying) our conceptualization of OOP assuming the wrong "definition" adopted by some technician writing the manual of a well known class based OO platform.

Sorry for stating something in such an old post, but the issue is always valid.

Solution 5

Though https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.2 shows that Private Members are not inherited. Actually, it is inherited by subclass. When we use debuggers to trace variables, it will show the private members under the label of "inherited", so just try it. there is another post discussing this question, and most of them think not inherited, which misleads many people, including me at first.

Share:
35,660

Related videos on Youtube

Mandy M
Author by

Mandy M

Updated on February 26, 2020

Comments

  • Mandy M
    Mandy M about 4 years

    I was told that for a Java subclass it can inherit all members of its superclass. So does this mean even private members? I know it can inherit protected members.

    Can someone explain this to me. I am now totally confused.

  • sharakan
    sharakan about 12 years
    Comes down to what "inherit" means. The doc @roadRunner linked to has it both ways: near the beginning it says "A subclass inherits all the members (fields, methods, and nested classes) from its superclass." then contradicts itself saying it does not inherit private members. Personally, I think they are inherited because they are there, they're just not directly accessible. I'm curious if there's a real definition of what 'inherit' means to Java, or perhaps OO in general.
  • gkakas
    gkakas almost 12 years
    @sharakan: today we have only a defacto definition.
  • gkakas
    gkakas almost 12 years
    So if we would compare the two alternatives that seem to emerge as defacto definitions, one car see the following: assuming one that states that private members are not inherited is completely misleading and dangerous for a new developer who thinks that superclass private members (state and behavior elements) disappeared. As such only one of the definitions is safe to assume. So there is no issue of "other definition" which was the basis of my original message ("no matter of definition"). The other definition makes no assumptions ;-)
  • Vishy
    Vishy over 5 years
    To clarify, all fields and methods still exist for sub classes but they are only accessible indirectly via a non private method which can access them (or reflection)
  • Giorgi Tsiklauri
    Giorgi Tsiklauri almost 3 years
    @PeterLawrey this is a very very important point for everyone who is keen to understand the language architecture in a deep way. My guess is, that all the members of the supertype(s) (including private ones) are allocated in the heap, into the address/scope of one, very same subclass instance (debugger shows superclass private members as part of the child class.. and as far as I know, during instantiation of the child class, respective super class instances are NOT created separately.. rather their members are included into the instance of child class).. they're just unavailable directly.