Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading