About sealed classes and interfaces
Starting Java 17 we can now allow additional class modifiers like sealed, non-sealed etc.
A sealed class or interface can be extended or implemented only by those classes and interfaces permitted to do so.
Following are the keywords related to sealed classes.
New Keywords
Earlier we had only two options, allow subclasses to inherit the parent class or interface or not at all. In the later case using Final class modifier. Using sealed we can take a more controlled middle path where the Parent Class or Interface can dictate the Sub classes which can inherit from the Class.
Defining sealed class (Two Styles)
Style One: Using permit keyword
using the class modifiers sealed and permits we can create sealed classes.
In the example bellow we are Defining abstract sealed class Tesla which permits three known subclasses Model3, ModelS and TeslaSUV.
Tesla
package java17.sealed;
public abstract sealed class Tesla permits Model3, ModelS, TeslaSUV{
public abstract Integer maxRange();
public String basePrice() {
return "25000 USD";
}
}
//Subclass 1
public final class Model3 extends Tesla {
@Override
public Integer maxRange() {
return 200;
}
}
//Subclass 2
public final class ModelS extends Tesla {
@Override
public Integer maxRange() {
return 400;
}
}
//Subclass3 (non-sealed)
public non-sealed class TeslaSUV extends Tesla {
@Override
public Integer maxRange() {
// TODO Auto-generated method stub
return null;
}
}
Style Two: Using member classes
In the following example we are creating a sealed class BMWCars and three member classes.
BMWCars
package java17.sealed;
public sealed class BMWCars {
public final class BMW3 extends BMWCars implements ElectricVehicle{
}
public final class BMWI extends BMWCars implements Vehicle {
}
public non-sealed class BMWJV extends BMWCars implements Vehicle {
}
}
Rules for Defining Sealed Classes or Interfaces
Both Class and Interface can be marked with sealed.
Inherited child classes can be marked with either final, sealed and non-sealed.
Every permitted subclass must directly extend the sealed class.
A permitted subclass may be non-sealed so that it is open for extension by unknown subclasses.
Summary
With introduction of sealed classes we can define the known subclasses of an abstract class. In other words now we can enforce extension of classes that is known in compile time. It allows us to have greater control of class proliferation and improve security.
No comments :
Post a Comment
Please leave your message queries or suggetions.