为什么在 Java 中不能有受保护的抽象类? [英] Why can't you have a protected abstract class in Java?

查看:44
本文介绍了为什么在 Java 中不能有受保护的抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类,它看起来像:

I have an abstract class which looks like:

abstract class AbstractFoo implements Bar {
  //Code goes here
}

但是,当我尝试使 AbstractFoo 受保护时,我收到一个错误编译时错误,抱怨它是一个非法修饰符.

However when I try to make AbstractFoo protected I get an error compile time error complaining that it is an illegal modifier.

protected abstract class AbstractFoo implements Bar {
  //Code goes here
}

为什么在 Java 中不能有受保护的抽象类?

Why can't you have a protected abstract class within Java?

我应该提到这不是普通的 Java,实际上是 Blackberry/J2ME.

I should probably mention that this is not vanilla Java and is actually Blackberry / J2ME.

推荐答案

正如许多其他人所指出的,这里的限制与您的类是抽象的这一事实无关,而是与您选择使用的可见性修饰符有关.请记住这些可见性修饰符的含义:

As many others have noted, the restriction here has nothing to do with the fact that your class is abstract, but rather in the visibility modifier you have chosen to use. Keep in mind what each of these visibility modifiers means:

对于您在其中使用关键字的类...

  • 私有:仅对本课程可见

(默认/包私有):仅对此类及其包中的类可见

(default/package private): Only visible to this class and classes in its package

protected:对此类、其包中的类以及此类的子类可见

protected: Visible to this class, classes in its package, and subclasses of this class

public:对任何班级可见

顶级类不能被声明为私有,因为这样就没有人能够访问它们了.

Top level classes cannot be declared private, because then nothing would ever be able to access them.

但您的问题源于为什么它们可能不被声明为受保护.很明显,受保护的顶级类(如果它能够存在)对其自身可见(每个类对自身可见).同样清楚的是,受保护的顶级类对其包中的类是可见的.然而,让它对其子类可见是很棘手的.应该允许哪些类继承我们的受保护类?

But your question stems around why they may not be declared protected. It is clear that a protected top-level class (were it able to exist) would be visible to itself (every class is visible to itself). It is also clear that a protected top-level class would be visible to classes in its package. However, making it visible to its subclasses is tricky. Which classes should be allowed to inherit our protected class?

如果是所有这些,那么我们的类也可能是public,因为那样我们就说任何类都有权访问我们的受保护类.如果它们都不是,那么我们的类也可能是 package-private,因为只满足其他两个条件(对自身和包中的东西可见).并且它不能是其中一些",因为我们需要一种定义哪些类可以访问它的方法,这就是可见性修饰符的首要用途.

If it is all of them, then our class might as well be public, because then we're saying that any class has the right to access our protected class. If it's none of them, then our class might as well be package-private, since only the other two conditions (being visible to itself and things in its package) are met. And it can't be "some of them," since we would need a way of defining which classes can access it, which is what the visibility modifier was for in the first place.

因此,由于这些原因,顶级类不能私有受保护;它们必须包私有公共.

So for these reasons, top-level classes cannot be private or protected; they must be package-private or public.

这篇关于为什么在 Java 中不能有受保护的抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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