Java Lab internal 4B1
Name – Harsh Vardhan Singh
Roll No. - 2200290110075
WAP to implement sealed classes with functional interface.
Code – :
sealed class Shape permits Circle, Rectangle {
// common shape methods can be defined here if needed
final class Circle extends Shape {
private final double radius;
public Circle(double radius) {
this.radius = radius;
public double getRadius() {
return radius;
final class Rectangle extends Shape {
private final double width;
private final double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
public double getWidth() {
return width;
public double getHeight() {
return height;
@FunctionalInterface
interface ShapeOperation {
double calculate(Shape shape);
public class ShapeCalculator {
public static void main(String[] args) {
ShapeOperation areaOperation = (Shape shape) -> {
if (shape instanceof Circle) {
Circle circle = (Circle) shape;
return Math.PI * circle.getRadius() * circle.getRadius();
} else if (shape instanceof Rectangle) {
Rectangle rectangle = (Rectangle) shape;
return rectangle.getWidth() * rectangle.getHeight();
throw new IllegalArgumentException("Unknown shape");
};
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);
System.out.println("Circle area: " + areaOperation.calculate(circle));
System.out.println("Rectangle area: " +
areaOperation.calculate(rectangle));
Output : -
Circle area: 78.53981633974483
Rectangle area: 24.0