brace yourselves java 17 is coming (4/6)

hands on: java 15


last time, we talked about the java 14 and null pointer exception messages and records. in java 15, there is an addition to records, the sealed and non-sealed keyword. let's see what it can do for us.


sealed class

a sealed class is very similar to java 9's jigsaw module system. we can now tell which classes are allowed to implement/extend an interface or extend an abstract class by prefixing class or record keyword with the sealed keyword. so an interface can be defined like that:

sealed interface Car permits Audi, Vw {
    String name();
}

only two classes are allowed implementing or extending from the car interface. an implementation can be specified like following:

public record Audi(String name) implements Car {
}

in case of record, we don't need the sealed prefix, since record is always a final immutable class, the definition will be redundant. we can also use the old notation to declare our class immutable, see here:

public final class Vw implements Car {

    private final String name;

    public Vw(final String name) {
        this.name = name;
    }

    public String name() {
        return name;
    }
}

once sealed is used in the implementation hierarchy, we're always forced to use sealed, non-sealed, final or record keyword.

summary

before java 15, we can only allow inheritance for all classes or for none. with this feature we're allowed to give permission to a hand full of classes instead opening for the entire world. it's not the greatest feature, but i am confident, that it might help some of us in the near future.


so what do you think about the changes? do you like it and will try to adapt them in upcoming process, or will you wait for the next lts before using it? let me know.


see the full source code here: https://github.com/kmo-dev/java15

Recent Posts

See All