How to control what classes can extend my class in Java

119 views Asked by At

So I was asked this question in interview that if I have a class A how do I restrict which classes will be able to extend A. For example if I want only class C and E to be able to extend A and classes B and D should not be able to do so. I mentioned about bounded wildcards in generics but I think that didn't answer the question. I am not aware about any new feature added in newer versions of Java. Please let me know what is the correct answer to that.

1

There are 1 answers

4
aled On BEST ANSWER

Sealed classes seems to be one method to restrict which classes can extend another. This feature is available since Java 17.

Contraints:

  • All permitted subclasses must belong to the same module as the sealed class.
  • Every permitted subclass must explicitly extend the sealed class.
  • Every permitted subclass must define a modifier: final, sealed, or non-sealed.

Example:

public abstract sealed class Vehicle permits Car, Truck {...}

This restricts that only classes Car or Truck can extend Vehicle.