javaoopsealed-class

How to control what classes can extend my class in Java


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.


Solution

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

    Contraints:

    Example:

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

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