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?
Catasfinal, no other class can extendCat.Duckasnon-sealed, any class can extendDuck.When marking a class as
sealed, all directly extending classes (the ones after thepermitsclause) have to be marked either asfinal,sealedornon-sealed:Marking a class that extends a
sealedclass assealed, applies the same effect on it: Only classes specified after thepermitsclause are allowed to extend it.non-sealedjust "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.finalis effectively the same assealedwithout any class specified after thepermitsclause. Notice that specifying nothing afterpermitsis not possible, sosealedcannot replacefinal.