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

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

问题描述

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.

查看代码

一个类有一个包私有 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() { }
}

两个类,它继承一个类,而 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 方法的可见性是不合法的。

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.

为什么降低可见性成为问题?

考虑我们要使用的情况 class:

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.
  }
}

这里,调用 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.)

现在,如果我们要实例化两个对象并将其放在 obj 类型的变量一个

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天全站免登陆