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.
Asked
Active
Viewed 52 times
1 Answers
1
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.

aled
- 21,330
- 3
- 27
- 34
-
Thanks, would you recommend a book I could read to update myself on all the new features in recent versions. I am stuck at Java 8. – Shivam... Jun 02 '23 at 12:49
-
1I'm sorry, I'm not aware of any. Also note that [recommendations are off-topic](https://stackoverflow.com/help/on-topic) in Stackoverflow. – aled Jun 02 '23 at 13:52
-
@Shivam..., I recommend any Java book by _O'Reilly Media_, they cover a wide range of Java topics; _"core Java"_ is the term you're looking for, and will typically cover class inheritance well. Additionally, any book by _Oracle_, the company which currently owns _Java_, is typically a good choice. Additionally, if you're looking for this specific mechanism, a _"sealed class"_, you'll want a book specific to Java 17 or after. – Reilas Jun 02 '23 at 14:09
-
1Check out [Java Magazine](https://blogs.oracle.com/javamagazine/) which is an `Oracle` publication. Another possibility is [JavaWorld](https://www.infoworld.com/category/java/) which is a subcategory of `InforWorld.com.` – WJS Jun 03 '23 at 14:23