简体   繁体   English

抽象私人内部阶级

[英]abstract private inner class

I am preparing for an Oracle examination and answered incorrectly to the following question: 我正在准备Oracle考试,但对以下问题的回答不正确:

the combination abstract private is legal for inner classes 组合摘要private对于内部类是合法的

As it turns the answer is true, I answered false, as I could not find any use cases for having an abstract private inner class, that cannot be overridden from subclasses. 答案是正确的,我回答是错误的,因为我找不到用于抽象私有内部类的用例,这些内部私有类不能从子类中覆盖。 Can someone explain, why/for what do we have that in the language? 有人可以解释一下,为什么/为什么要用这种语言吗?

The Java language specification defines the meaning of private members as follows: Java语言规范定义私有成员的含义如下:

Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. 否则,成员或构造函数将被声明为私有,并且仅当且仅当它出现在封装成员或构造函数的声明的顶级类(第7.6节)的主体内时,才允许访问。

That is, a private inner class is accessible (and may be subclassed) from any code residing in the same source file. 也就是说,可以从驻留在同一源文件中的任何代码访问(并且可以将其私有化)私有内部类。 For instance, you could do: 例如,您可以执行以下操作:

public class C {

   private abstract class A {
       abstract void foo();
   }

   void bar() {
       new A() {
           @Override void foo() {
               // do something
           }
       }
   }
}

It is interesting to note that a method declared private can not be overriden, but methods in private classes can be. 有趣的是,不能重写声明为private的方法,但是可以重写private类中的方法。

the combination abstract private is legal for inner classes 组合摘要private对于内部类是合法的

Its a bit confusing but the rule is that an inner class can't have an abstract private method. 有点令人困惑,但是规则是内部类不能具有抽象的私有方法。

if exam is saying the contrary then its wrong. 如果考试说的相反,那就错了。

UPDATE : if what you mean is in class declaration, then answer is true, check this valid piece of code... 更新 :如果您的意思是在类声明中,则答案为真,请检查此有效代码段...

public class MyOuter {
    abstract private class MyInner {
        //the combination abstract private is legal for inner classes: TRUE
    }
}

To know why or when use it, check the suggested link , there is a good explanation about this... 要知道为什么或何时使用它,请查看建议的链接 ,对此有很好的解释 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM