How can I make a class not extendable without using the final keyword?
How can I achieve this without the final
keyword? What must I change to the constructors?
public final class testName {
testName() {
开发者_高级运维//do something
}
}
If you make all your Constructors private
, then the class will also no longer be extendable.
public class TestName {
private TestName(){do something}
}
To see why, check section 3.4.4.1, 'The default constructor'. By declaring your private default constructor, the last sentence of the paragraph holds:
Such a [private] constructor can never be invoked from outside of the class, but it prevents the automatic insertion of the default constructor.
So effectively by declaring a constructor in the superclass that is not accessible, there is no (other) constructor that your subclass could call and thus Java prevents compilation.
If the constructor should fail due to code inserted at the "//do something" comment, then throw an exception.
The other options -- final class or private constructor -- are better choices, generally, because they report the error at compile time, rather than run time. But if the failure should be conditional, or if someone is testing your knowledge, then throwing an exception is the usual approach.
[Expert question: If the constructor throws an exception, is there any way the program can still end up with a reference to the newly created instance? (Hint: Yes.) ]
You can make private constructor of that class.
精彩评论