You are here
Home > java >

JDK 15 Features

JDK 15 FeaturesJDK 15 features released on 15th Sept, 2020. After 25 years of innovation, Java continues to be the #1 programming language, used by over 69 percent of full-time developers worldwide. The latest Java Development Kit (JDK) delivers new functionalities to improve developer productivity & security. As a developer we should have knowledge of the features of new release, at least which may be important to our development part. JDK 15 features also may have an important role in java technical interview process. Not only JDK 15 but features of other previous versions also can play an important role in the interview.

Besides cracking the java technical interview we should also have an idea on the growth of our programming language with respect to other popular languages in the industry. Here in this article we will focus in detail on the features which are important as programming point of view. One important feature, a new modifier of class/interface ‘sealed’ is in proposal of preview feature of JDK 15. Text blocks which were in the list of preview feature in JDK 14 are now final feature in this release. Further let’s start learning JDK 15 features.

Sealed class (Preview Feature)

What is a sealed class/interface?

It is a preview feature introduced in JDK 15. As the word  ‘sealed’ suggests, there is something which has restrictions. Till previous versions of JDK, we could extend any class from the super class without any restriction if super class is non final. But now we have the provision to declare the list of subclasses which only can extend from a super class. This is the place where sealed comes into the picture.

sealed is a modifier which restricts subclassing. It has an optional permits list where we can declare the types which only are open for subclassing, nothing else. If we don’t declare optional permits list, it means the declared sealed type is not open for subclassing at all. We can apply it with a class, abstract class or interface. Of course, we can seal a class or an interface(restrict from subclassing) by applying the ‘sealed’ modifier to its declaration.

sealed interface Animal
permits Dog, Cat, Tiger { ... }

The above code represents that only Dog, Cat & Tiger can extend or implement Animal. We can’t extend/implement Lion from Animal at all. From the above code if we further work on sub-types, below are the conclusions.

sealed interface Dog extends Animal{ }         => Since interface Dog is sealed, no other class/interface can implement/extend interface Dog.

sealed class Dog implements Animal{ }         => Since class Dog is sealed, no other class can extend class Dog.

What does non-sealed mean ?

non-sealed modifier indicates that class or interface has no restrictions on subclassing. We need to apply this modifier if a class or interface doesn’t have any restriction on subclassing.

non-sealed class Dog implements Animal{ }  => Since class Dog is non-sealed, Any other class can extend class Dog.

non-sealed interface Dog extends Animal{ }  => Since interface Dog is non-sealed, Any other class/interface can implement/extend interface Dog.

Sealing is a generalization of finality; where a final type has no subtypes, a sealed type can have no subtypes beyond a fixed set of co-declared subtypes. In below code snippet we have enough exercise on sealed type to get hold on it.

TestSealedJDK15.java

public class TestSealedJDK15 {

}

// classes or interfaces started from modifier sealed or non-sealed should have annotation @SuppressWarnings("preview")

@SuppressWarnings("preview")
sealed interface Animal
permits Dog, Cat, Tiger { }

@SuppressWarnings("preview")
non-sealed class Dog implements Animal{} // allowed , The class Dog with a sealed direct superclass or a sealed direct superinterface Animal should be declared either final, sealed, or non-sealed

@SuppressWarnings("preview")
non-sealed interface Dog1 extends Animal{} // not allowed, The type Dog1 extending a sealed interface Animal should be a permitted subtype of Animal

//class Dog implements Animal{}

class Dog2 extends Dog{}

@SuppressWarnings("preview")
sealed interface Cat extends Animal permits Cat1{}

final class Cat1 implements Cat{}

@SuppressWarnings("preview")
non-sealed class Tiger implements Animal{} // not allowed , The class Tiger with a sealed direct superclass or a sealed direct superinterface Animal should be declared either final, sealed, or non-sealed

class Tiger1 extends Tiger{}

@SuppressWarnings("preview")
sealed abstract class Parent permits Child1, Child2 {}

@SuppressWarnings("preview")
non-sealed class Child1 extends Parent{}

@SuppressWarnings("preview")
sealed class Child2 extends Parent{}

class Child3 extends Child2{}  // not allowed, The class Child3 with a sealed direct superclass or a sealed direct superinterface Child2 should be declared either final, sealed, or non-sealed

class Child4 extends Child1{}  // allowed

@SuppressWarnings("preview")
non-sealed class Child5 extends Child1{}  // not allowed, A class Child5 declared as non-sealed should have either a sealed direct superclass or a sealed direct superinterface

@SuppressWarnings("preview")
sealed class MyClass{}  // not allowed , Sealed class lacks the permits clause and no top level or nested class from the same compilation unit declares MyClass as its direct superclass.

What is the benefit of creating sealed classes/interfaces?

If you are creating an API of a project, you can restrict other developers to extend your class/interface unnecessarily. In other words, if an API owner wants to defend the integrity of the API, It is possible. The other, less obvious benefit is that it potentially enables complete analysis at the use-site, such as when switching over type patterns in a sealed type.

What are the common rules to use sealed type?

1) classes or interfaces started from modifier sealed or non-sealed should have annotation @SuppressWarnings(“preview”) to ignore the compilation errors.
2) We can declare permitted child class either as a sealed or non-sealed or final
3) Similarly, we can declare permitted child interface either as a sealed or non-sealed
4) In case of non-sealed classes or non-sealed interfaces there is no need to apply permits keyword.

What all general questions can be asked in interviews from this ‘sealed’ topic ?

Furthermore, we can have below questions in the interviews if interviewer wants to check your knowledge on JDK 15 version updates.
If you already gone through the above explanation on ‘sealed’ modifier, you will easily answer all the questions.
Questions are :

1) How can we restrict an interface to be extended by any other interface?
2) How can we restrict an interface to be implemented by any other class?
3) How can we restrict any class to be sub-classed by any other class without using final keyword?

Needless to say, Answer to all questions in only ‘sealed’ modifier.

Trust me, the new features of other previous versions are also equally important. Hence we can’t ignore them at all. If you are the learner in java, at least you should know the names of new features. Likewise if you are an experienced developer, you should also know the internals of each & every new features. Having knowledge of new features just indicates that you are aware of the present updates of language you are working in. On the other hand, there will be an impression that you can work easily with the latest concepts & codes and will also be able to minimize the lines of code.

Records (Second Preview Feature)

Records were proposed in JDK 14 as a fist preview feature. Now they are proposed to re-preview the feature in JDK 15 both to incorporate clarifications as per provided feedback and to support additional forms of local classes and interfaces in the Java language.

The keyword ‘record’ is a special class type in java like enum. So it is known as record type. In other words, Records are a new kind of type declaration in the Java language. A record is a data class that will store data. It will help to reduce boilerplate code & create simple, concise classes immediately.

Records with Sealed Types

Records work well with Sealed types. Please note that records & sealed both are still preview features. Further, if both becomes final features in near future we will see some implementations like the below code snippet.

TestRecordWithSealed.java

public class TestRecordWithSealed {

}

@SuppressWarnings("preview")
sealed interface MathematicalOperation 
	permits AddOperation,SubtractOperation,MyOperation,OtherOperation {
}

@SuppressWarnings("preview") 
record AddOperation(int i, int j) implements MathematicalOperation {
	
}

@SuppressWarnings("preview")
record SubtractOperation(int i, int j) implements MathematicalOperation {
	
}

@SuppressWarnings("preview")
record MyOperation(MathematicalOperation mo) implements MathematicalOperation {
	
}

@SuppressWarnings("preview")
record OtherOperation(AddOperation ao, SubtractOperation so) implements MathematicalOperation {
	
}

Changes in Reflection API (java.lang.Class)

The plan is to add following two public methods into java.lang.Class:

1) RecordComponent[] getRecordComponents() : The method getRecordComponents() returns an array of java.lang.reflect.RecordComponent objects. The elements of this array correspond to the record’s components, in the same order as they appear in the record declaration. Further, We can extract additional information from each element in the array, including its name, annotations, and accessor method.
2) boolean isRecord() : The method isRecord returns true if the given class was declared as a record. (Compare with isEnum.)

Furthermore, if you want to have deep idea on coming preview features on Records type kindly visit  openJDK documentation.

Text Blocks

In Java, embedding a snippet of HTML, XML, SQL, or JSON in a string literal “…” usually requires significant editing with escapes and concatenation before the code containing the snippet will compile. The snippet is often difficult to read and difficult to maintain.

A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, making inline multi-line Strings more readable and gives the developer control over the format when desired. Text blocks were initially in JDK 12 proposal target but eventually didn’t appear in that release. Then they were first time proposed in JDK 14 as a preview feature but the feedback suggested that the text blocks should again be previewed in JDK 14 with the addition of two new escape sequences.

Accordingly, feedback on JDK 14 suggested that text blocks were ready to become final and permanent in JDK 15 with no further changes. Below code snippet shows correct use of Text Blocks.

TestTextBlock.java
public class TestTextBlock {
	
	public static void correctExample() {
		String s = """
		Hello
		World
				""";
		System.out.println(s); // Code compiles and prints both "Hello" "World" as it is - notice that "World" is printed in the next line.
	}
	
	public static void incorrectExample() {
		String s = """
				Hello
				World
						"";  // Compilation error - text block is not closed properly
	
	   System.out.println(s);
	}
	
}

Pattern Matching for instanceof (Second Preview Feature)

In fact, Pattern Matching allows common logic in a program, namely the conditional extraction of components from objects, to express them more concisely and safely. This feature was proposed in JDK 14 as a review feature. This JEP (JDK Enhancement Proposal) proposes to re-preview the feature in JDK 15, with no changes relative to the preview in JDK 14, in order to gather additional feedback.

Other Features in JDK 15

Below are the other features related to internal architecture & performance enhancements.

Edwards-Curve Digital Signature Algorithm (EdDSA)

Hidden Classes

Remove the Nashorn JavaScript Engine

Reimplement the Legacy DatagramSocket API

Disable and Deprecate Biased Locking

ZGC: A Scalable Low-Latency Garbage Collector

Shenandoah: A Low-Pause-Time Garbage Collector

Remove the Solaris and SPARC Ports

Foreign-Memory Access API (Second Incubator)

Deprecate RMI Activation for Removal

How to set up JDK 15 environment in Eclipse ?

You can visit our other article ‘How To Setup JDK 15 Environment In Eclipse ?

Conclusion

To summarize, in this article we have gone through the JDK 15 features which are crucial to enhance our programming knowledge. If any preview feature concludes to its final feature, we will update our post accordingly. We will also provide the details of other features which will be important in near future as an update of this post.

Also if you are interested to go through JDK 14 features, you can get it as a separate article JDK 14 Features. Moreover, if you want to learn JDK features starting from 1.0 to 7, kindly visit the Java Features Before JDK 8. For JDK 8 features visit the link JDK 8 Features. Additionally, for JDK 10 to Other higher versions, you can visit the link Java Features After JDK 8 as well.

How to setup JDK 15 environment in Eclipse ?

close

5 thoughts on “JDK 15 Features

  1. Pingback: Robin R

Leave a Reply

Top