Return to site

☕🎓JAVA CERTIFICATION QUESTION: module-info.java and sealed classes

· java,ocp

Imagine you are working on a new unit testing framework for Java classes and start with the following folder hierarchy:

src

└───com

└───acme

└───test

└───Test.java

There’s a single base Java class inside the project.

Which statements correctly describe the conditions when the code compiles successfully? Choose two.

A) If you put the StaticTest and DynamicTest classes in the com.acme.test package, you do not need to provide module-info.java.

B) If you put the StaticTest and DynamicTest classes in the com.acme.test.util package, you do not need to provide module-info.java.

C) If you provide module-info.java, you must put the StaticTest and DynamicTest classes in the same module with the Test class.

D) If you provide module-info.java, you must put the StaticTest and DynamicTest classes in the com.acme.test package.

E) If all modules have a proper module-info.java file, you may put the StaticTest and DynamicTest classes in different modules.

#java #certificationquestion #ocp

 

 

Answer: A, C

Sealed classes bring exhaustiveness, clarity, and security.

They make it very clear that only a specific set of subtypes are assignment-compatible with the sealed base type.

But Java 17’s JEP 409 (sealed classes) makes the following comment:

"The classes specified by permits must be located near the superclass:

either in the same module (if the superclass is in a named module)

or in the same package (if the superclass is in the unnamed module)."

Hence:

1) All elements of the sealed-type hierarchy must be in the same module.

2) If the code that’s compiled and run is not in an explicit module

(that is, the code on the classpath is in the unnamed module, which is not explicit),

the elements of the hierarchy must be in the same package.

So it’s mandatory that all elements of the sealed hierarchy be in the same package if the code is not running in a named module.

That makes correct the statement A.

Also, it’s permissible to place members of the sealed hierarchy in different packages only if the code is running in a named module.

That makes incorrect statement B.

Statement C is also correct because, permitted types must be as close as possible to sealed types, and the most permissive interpretation is that all the types must be in the same module.

Statement D is incorrect because it is not mandatory to put all the permitted types into the same package when you build a sealed-type hierarchy with a module-info.java file.

Statement E is also incorrect because you can never spread a sealed type and its permitted types across different modules.