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

前端 未结 5 852
情书的邮戳
情书的邮戳 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 08:14

    It would break polymorphism.

    If you have a Two instance stored in a Two variable, then it would make sense that foo cannot be called. But if you store a Two instance in a One variable, you only know about One. But One's have a public foo, and that can be called. This would be an inconsistency and would be really weird.

提交回复
热议问题