为什么我们不能用私有扩展类方法覆盖基类方法? [英] Why can’t we override a base class method with private extended class method?

查看:93
本文介绍了为什么我们不能用私有扩展类方法覆盖基类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class One {
    void foo() { }
}
class Two extends One {
    private void foo() { /* more code here */ }
}

为什么上面的代码片段是错误的?

Why is the above snippet of code wrong?

推荐答案

我将尝试结合其他答案中的思想来提出一个答案.

首先,让我们看一下代码中正在发生的事情.

First off, let's take a look at what's going on in the code.

查看代码

One类具有程序包专用的foo方法:

The One class has a package-private foo method:

class One {
    // The lack of an access modifier means the method is package-private.
    void foo() { }
}

Two类是One类的子类,并且foo方法被覆盖,但是具有访问修饰符private.

The Two class which subclasses the One class, and the foo method is overriden, but has the access modifier private.

class Two extends One {
    // The "private" modifier is added in this class.
    private void foo() { /* more code here */ }
}

问题

Java语言不允许子类降低子类中方法,字段或类的可见性,因此,降低foo方法可见性的Two类是不合法的.

The Java language does not allow subclasses to reduce the visibility of a method, field or class in a subclass, therefore, the Two class reducing the visibility of the foo method is not legal.

为什么降低能见度是一个问题?

考虑我们要使用One类的情况:

Consider the case where we want to use the One class:

class AnotherClass {
  public void someMethod() {
     One obj = new One();
     obj.foo();  // This is perfectly valid.
  }
}

在这里,在One实例上调用foo方法是有效的. (假设AnotherClass类与One类位于同一程序包中.)

Here, calling the foo method on the One instance is valid. (Assuming that the AnotherClass class is in the same package as the One class.)

现在,如果要实例化Two对象并将其放置在类型为Oneobj变量中怎么办?

Now, what if we were to instantiate the Two object and place it in the obj variable of the type One?

class AnotherClass {
  public void someMethod() {
     One obj = new Two();
     obj.foo();  // Wait a second, here...
  }
}

Two.foo方法是私有的,但是One.foo方法将允许访问该方法.我们这里有问题.

The Two.foo method is private, yet, the One.foo method would allow the access to the method. We've got a problem here.

因此,在考虑继承时允许降低可见性没有多大意义.

Therefore, it doesn't make much sense to allow reduction of visibility when taking inheritance into account.

链接

  • Controlling Access to Members of a Class - Explanations of access modifiers from The Java Tutorials.

这篇关于为什么我们不能用私有扩展类方法覆盖基类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆