Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a class not extendable without using the final keyword?

Tags:

java

class

How can I achieve this without the final keyword? What must I change to the constructors?

 public final class testName {
     testName() {
        //do something
     }
 }
like image 622
MoglisSs Avatar asked Aug 01 '11 12:08

MoglisSs


People also ask

How do you make a class non extendable?

You can use final keyword in java, sealed in C# to make a class non-extendable.

Which of the following keyword is used to make a class non extendable in Java?

In Java, we use the final keyword to prevent some classes from being extended.

What is a class that Cannot be extended?

You cannot extend a final class.


1 Answers

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.

like image 184
emboss Avatar answered Sep 24 '22 22:09

emboss