Thursday 28 July 2022

Sealed classes, interfaces and records

Sealed classes, interfaces work well with records. To demonstrate the example, I am defining a sealed interface Operation, and two record types Add, Mul will implement this sealed interface.

 


Operation.java

package com.sample.app.recrods;

public sealed interface Operation permits Add, Mul{

    public Long operation();
}

Add.java

package com.sample.app.recrods;

public record Add(int... a) implements Operation {

    @Override
    public Long operation() {
        if(a == null || a.length == 0) {
            return null;
        }
        
        long sum = 0;
        
        for(int ele : a) {
            sum += ele;
        }
        
        return sum;
    }

}

Mul.java

package com.sample.app.recrods;

public record Mul(int... a) implements Operation {

    @Override
    public Long operation() {
        if (a == null || a.length == 0) {
            return null;
        }

        long result = 1;

        for (int ele : a) {
            result *= ele;
        }

        return result;
    }

}

SealedAndRecordDemo.java

package com.sample.app;

import com.sample.app.recrods.Add;
import com.sample.app.recrods.Mul;

public class SealedAndRecordDemo {

    public static void main(String[] args) {
        Add add = new Add(new int[] { 2, 3, 5, 7 });
        Mul mul = new Mul(new int[] { 2, 3, 5, 7 });

        System.out.println("Sum of first four primes : %d".formatted(add.operation()));
        System.out.println("Multiplication of first four primes : %d".formatted(mul.operation()));
    }

}

Output

Sum of first four primes : 17
Multiplication of first four primes : 210

 

References

https://openjdk.org/jeps/360

https://openjdk.org/jeps/384

 



 

Previous                                                 Next                                                 Home

No comments:

Post a Comment