DEV Community

Cover image for My favourite 28 features in Java as it turns 28

My favourite 28 features in Java as it turns 28

Sendil Kumar on May 25, 2023

Java turned 28 this week! Here are my 28 favourite features/APIs in it. What are your favourite features/APIs comment below? ...
Collapse
 
siy profile image
Sergiy Yevtushenko

For some strange reason, sealed classes are considered a funny way to enabled/disable inheritance. But the ability of sealed classes to restrict inheritance is a secondary feature. The main purpose of sealed classes is the creation of the sum types. Before sealed classes, the only way to create sum types in Java was to use enums. But they have limitations (for example, each type has exactly one immutable instance, enums can’t be generic, etc.). Sealed classes fill this gap. And only here the ability to limit inheritance gets really useful. For example, now one can implement Optional<T> as a sealed interface which has exactly two implementations - Some<T> and None<T> and the whole implementation is protected from extension and/or inheritance, hence protected from incorrect or malicious use. An example of such an implementation can be found here

Another advantage of such an implementation is that it is suitable for pattern matching:

void patternMatchingIsSupported() {
    var optionValue = Option.present(123);

    switch (optionValue) {
        case Some some -> assertEquals(123, some.value());
        case None none -> fail("Unexpected value: " + none);
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sendilkumarn profile image
Sendil Kumar

I agree! I have mentioned that in the blog post itself.

"Both Record and Sealed classes are algebraic data types (ADT). ADTs are a fancy way of saying composite types (the type formed by combining other types). Record classes are product types. Sealed classes are sum types.

Being sum type, the Sealed classes make it easy for the compiler to understand its various type forms."

Collapse
 
prsaya profile image
Prasad Saya

Two notable ones are: (1) Language feature improvements in Java 7, like the try-with-resources and exception handling (e.g., multi-catch) made the coding simpler. (2) Importantly, the Java 8's Streams (and its integration with collections, file i/o, etc., ) and the new date and time APIs.

Collapse
 
sendilkumarn profile image
Sendil Kumar

Oh yeah! Try With Resources is another one!