简体   繁体   中英

What are final inner classes?

What does it means to declare a non-static inner class as 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. I found this link on google but even it doesn't explains it.

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. Marking classes final is sometimes done to let the compiler skip a virtual table lookup, but this is often regarded as premature micro-optimization.

It has the same semantics as an outer class being declared final: the class cannot be extended.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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