Private members in Java inheritance

后端 未结 5 657
执笔经年
执笔经年 2020-12-01 06:43

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.

C

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 07:31

    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.

提交回复
热议问题