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
?
Cat
asfinal
, no other class can extendCat
.Duck
asnon-sealed
, any class can extendDuck
.When marking a class as
sealed
, all directly extending classes (the ones after thepermits
clause) have to be marked either asfinal
,sealed
ornon-sealed
:Marking a class that extends a
sealed
class assealed
, applies the same effect on it: Only classes specified after thepermits
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 assealed
without any class specified after thepermits
clause. Notice that specifying nothing afterpermits
is not possible, sosealed
cannot replacefinal
.