Why can’t we override a base class method with private extended class method?

前端 未结 5 824
情书的邮戳
情书的邮戳 2021-01-06 07:22
class One {
    void foo() { }
}
class Two extends One {
    private void foo() { /* more code here */ }
}

Why is the above snippet of code wrong?<

5条回答
  •  心在旅途
    2021-01-06 07:51

    The given answers give you the technical explanation why you cannot extend One by Two. I would like to give you an understanding why this is not possible due to the object oriented pattern and not because of the language itself.

    Usually the class One is a general definition of a class with its accessors, the methods, to the outer world. Sublcasses which extend this class must provide the same accessors to the outer world. Two extends One in your example, what means, that Two provides the same accessors to the outer world like One does. If you would change the visibility of the accessors of One, the outer world could no longer access your class as they are used to do it with an object of type One.

提交回复
热议问题