Reputation: 694
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!
Upvotes: 12
Views: 9323
Reputation: 2190
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.
Upvotes: 0
Reputation: 727047
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.
Upvotes: 11
Reputation: 4056
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.
Upvotes: 0