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

前端 未结 5 859
情书的邮戳
情书的邮戳 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:59

    Because inheritance is a is a relationship. Anyone could refer to a instance of Two through a reference to One :

    One v = new Two();
    

    What would the program do if you called the foo method on the v reference? You broke the public contract of One, which guarantees that every instance of One has a (here package-protected) foo method. That's why the compiler forbids it.

提交回复
热议问题