Home > Back-end >  How to restrict inheritance in java more than one time?
How to restrict inheritance in java more than one time?

Time:10-31

Suppose there is Class A which is parent class and class B extends A. Now I should not allow to extend class A to class C(Class C extends A) or any other class. How to do that?

CodePudding user response:

That's why java-17 has sealed classes. This feature was added as a preview feature in java-15.

In your case you can do the following:-

public sealed class A permits B {

}

So it can be only extended by class B not C.

Helpful links:

https://docs.oracle.com/en/java/javase/15/language/sealed-classes-and-interfaces.html

http://openjdk.java.net/jeps/409

https://www.baeldung.com/java-sealed-classes-interfaces

What are sealed classes in Java 17

  •  Tags:  
  • java
  • Related