为什么你不能在Java的一个受保护的抽象类

为什么你不能在Java的一个受保护的抽象类

本文介绍了为什么你不能在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和实际上是黑莓/ 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: Visible to this class, classes in its package, and subclasses of this class

公开:可见的任何类

顶层类不能声明的私人后,因为再没有什么会永远能够访问它们。

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?

如果是所有的人,那么我们班很可能会成为公开,因为那时候我们说,任何类有访问我们的保护类的权利。如果这是他们没有的话,我们班很可能会成为包私人,因为只有其他两个条件(即在其包装可见自身的东西)都得到满足。它不可能是他们中的一些,因为我们需要的定义方式类可以访问它,这是可见度修饰符是摆在首位。

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的一个受保护的抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 19:32