I have the following sealed interface (Java 15):
public sealed interface Animal permits Cat, Duck {
String makeSound();
}
This interface is implemented by 2 classes:
public final class Cat implements Animal {
@Override
public String makeSound() {
return "miau";
}
}
public non-sealed class Duck implements Animal {
@Override
public String makeSound() {
return "quack";
}
}
Can someone tell me the difference between final
and non-sealed
? final
stops me from creating other sub-classes but what behavior does non-sealed
apply to Duck
?
Sealed class is declared using sealed keyword. Sealed classes allow to declare which class can be a subtype using permits keyword. A class extending sealed class must be declared as either sealed, non-sealed or final. Sealed classes helps in creating a finite and determinable hiearchy of classes in inheritance.
A Private class can only be accessed by the class it is defined and contain within - it is completely inaccessible to outside classes. A Sealed class can be accessed by any class, but can not be derived from.
The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class. The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual.
Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended. No class can be derived from a sealed class.
Cat
as final
, no other class can extend Cat
.Duck
as non-sealed
, any class can extend Duck
.When marking a class as sealed
, all directly extending classes (the ones after the permits
clause) have to be marked either as final
, sealed
or non-sealed
:
Marking a class that extends a sealed
class as sealed
, applies the same effect on it: Only classes specified after the permits
clause are allowed to extend it.
non-sealed
just "breaks the seal", so the effect doesn't have to be carried on down the hierarchy. The extending class is open (again) for being extended by unknown subclasses itself.
final
is effectively the same as sealed
without any class specified after the permits
clause. Notice that specifying nothing after permits
is not possible, so sealed
cannot replace final
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With