MoglisSs
MoglisSs

Reputation: 89

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
     }
 }

Upvotes: 5

Views: 8983

Answers (3)

Tushar Paliwal
Tushar Paliwal

Reputation: 301

You can make private constructor of that class.

Upvotes: 0

Jeff Grigg
Jeff Grigg

Reputation: 1014

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.) ]

Upvotes: 3

emboss
emboss

Reputation: 39650

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.

Upvotes: 15

Related Questions