简体   繁体   English

什么是最终内部课程?

[英]What are final inner classes?

What does it means to declare a non-static inner class as final ? 将非静态内部类声明为final什么意思?

I have tried many links on google and stackoverflow.com as well but all of them seem to be dealing about inner classes accessing final members not final inner classes itself. 我也尝试过在google和stackoverflow.com上的许多链接,但它们似乎都在处理访问最终成员的内部类,而不是最终内部类本身。 I found this link on google but even it doesn't explains it. 我在Google上找到了链接,但即使没有解释。

Thanx in advance! 提前感谢!

There is no semantic difference between making a top-level class final and making an inner class final : it tells the compiler that you cannot inherit from the class. 使顶层类为final和内部类为final之间没有语义上的区别:它告诉编译器您不能从该类继承。 Marking classes final is sometimes done to let the compiler skip a virtual table lookup, but this is often regarded as premature micro-optimization. 有时将类标记为final以使编译器跳过虚拟表查找,但这通常被视为过早的微优化。

It has the same semantics as an outer class being declared final: the class cannot be extended. 它具有与声明为final的外部类相同的语义:该类无法扩展。

Consider this example: 考虑以下示例:

public class MyClass {
  public class A {
  }
  public class B extends A {
  }
}

If you add the final modifier to A it will generate a compilation error. 如果将最终修饰符添加到A,将生成编译错误。

Well, inner classes are not any way different from outer classes in that context. 好吧,在这种情况下,内部类与外部类没有任何不同。 So the following code is perfectly valid. 因此以下代码是完全有效的。

class Outer {
 int some_member;

 class Inner {
 void method();
 }
}

class OuterExtendsInner extends Outer.Inner{

}

As we all know, the purpose of declaring a class final is that we prevent any outside intruder from subclassing the class and exploit its facilities, the same way we can do in case of inner classes. 众所周知,声明类的最终目的是防止外部入侵者对类进行子类化并利用其功能,这与内部类的情况相同。

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

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