Return to site

☕🎓JAVA CERTIFICATION QUESTION: Sealed class

· java,ocp

Which three statements accurately describe sealed classes in Java?

* Sealed classes cannot be declared as abstract.

* Sealed classes cannot be marked as final.

* In the permits clause of a sealed class, any specified class is permitted.

* In certain scenarios, a sealed class can be defined without a permits clause.

* Sealed classes can be nested.

#java #certificationquestion #ocp

Let's detail each statement:

* Sealed classes cannot be declared as abstract:

This statement is inaccurate.

Sealed classes can be declared as abstract, just like any other class.

Ex:

* Sealed classes cannot be marked as final:

This statement is accurate.

Sealed classes, by their nature, are designed to allow limited inheritance, so marking them as final would contradict this purpose.

They are intended to be extended by a predefined set of subclasses.

* In the permits clause of a sealed class, any specified class is permitted:

This statement is inaccurate.

The permits clause can reference only classes from the same package.

* In certain scenarios, a sealed class can be defined without a permits clause.

This statement is accurate.

The permits clause is optional if the selaed class and its direct subclasses are declared within the same file or the subclasses are nested within the sealed class.

* Sealed classes can be nested:

This statement is accurate.

Sealed classes can be defined as inner classes within other classes.

This allows for a more structured organization of code, especially when the sealed class is tightly related to the enclosing class.