Notice

╠ This is my personal blog and my posts here have nothing to do with my employers or any other association I may have. It is my personal blog for my personal experience, ideas and notes. ╣
Showing posts with label jdk15preview. Show all posts
Showing posts with label jdk15preview. Show all posts

Sunday, August 9, 2020

New way to create immutable object in Java ['record'] JEP 384: Records

As a Java developer, we use POJO every day in our coding. We have to write or generate codes of accessor methods and other methods like 'equals', 'toString' and 'hashCode' or use a library like Lombok. 

To make it more simplified Java introducing 'record'. Using which developer need not have to generate or write these code. 

Some of the features of these 'record' class. 

  • implicitly they are final so it cannot be extended or abstracted but can implement an interface. 
  • java.lang.Record is the superclass of record 
  • A record cannot define the native method. 
  • A record field(s)  is/are implicitly final
Let's see with an example. 

A simple record with no boilerplate code. It provides field accessor method, 'toString', 'equals' and 'hashCode' readily available. 

A record with multiple constructors and instance method. 

A record with constructor level validation, static method and override 'equals' method. 

In this class, we are accessing the field with the internal method and other methods like 'toString', 'equals' and 'hashCode'. 


Output 

To compile these codes 

javac --enable-preview --release 15 TestRecord.java


To Run these codes 

java --enable-preview TestRecord



Happy coding and keep learning!

Sunday, July 26, 2020

Now Java Developer can write their 'Will' [JDK15 JEP 360: Sealed Class (Preview)]

As a developer if you want to control who can extend your class or interface. 

In this enhancement of Java programming language, new keywords are introduced sealed, non-sealed and permit at the class level. 

A sealed class or interface can be extended or implemented only by those classes and interfaces permitted to do so. If you try to implement or extend to other class which is not permitted then the code will not compile. For example,
public sealed class Point permits Line


permit keyword defines which are the subclasses or interfaces can be extended or implemented from this class. For example, 
public sealed class Point permits Line
Point class only permits Line class to extend directly. 

A non-sealed class or interface will allow this class to be extended. 
For example,
public non-sealed class Line
Permitted class Line is open for any unknown class extension. 



To Compile

To Run




A permitted subclass must define whether it could be extended to a specific class (sealed) or open to any unknown class(non-sealed) or not open for any extension (final). 



When a not permitted class extend a sealed class. 





Happy Coding and keep learning!