Choosing your inheritors in Java 15

We all know Java as the Object-Oriented Programming language. Inheritance is one of the Core principles of Object-Orient Programming. Java supports the inheritance with Class extendability and Interface Implementation. You are free to extend any public class and add your own behaviour.

Here comes the sealed classes in java 15 to take the control back.

Consider the example below, Quadrilateral class is defined as sealed which permits Square and Rectangle only and not Circle.

public interface Shape { double area();  }

public sealed class Quadrilateral  permits Square, Rectangle {

   public void area(){
        System.out.println("This is Quadrilateral");
    }

}

//allowed
public final class Square extends Quadrilateral {

}

//non-sealed 
public non-sealed class Rectangle extends Quadrilateral {

}

//Compilation failure
class Circle extends Quadrilateral{}

Screen Shot 2020-11-15 at 4.18.38 PM.png

The subclass of a sealed class can have one of the modifiers sealed: can future restrict the classed to be extended non-sealed: opens up the extension to any class. final: class can't extend further in the hierarchy.

Need for the sealed class: The author of the sealed class as control over which classes can extend it. Provides a more declarative way than access modifiers.

note: Its a preview feature introduced part of java 15, Can continue or removed in a future releases.