Java has continuously evolved to include features that make code more expressive, concise, and safe. With Java 16, we saw the introduction of Record, and Sealed Classes arrived with Java 17 as a preview feature, becoming a permanent addition in Java 17 LTS. These features represent powerful new ways to structure data and control inheritance in Java. In this blog, we’ll explore what Records and Sealed Classes are, why they were introduced, and how to use them effectively.
1. Java Records: Simplifying Data Classes
What are Records?
In Java, creating a class to represent simple data often involves a lot of boilerplate code, including fields, constructors, getters, `toString()`, `equals()`, and `hashCode()` methods. Records are a new kind of class introduced to reduce this boilerplate by automatically generating these methods.
A Record in Java is a final, immutable data class that’s ideal for storing "plain data" without additional behavior.
Syntax of Records
Here's how simple it is to declare a record in Java:
java
public record Person(String name, int age) {}
In just one line, Java generates the following for you:
- A constructor matching the parameters.
- Getters for each field.
- `toString()`, `equals()`, and `hashCode()` implementations.
Benefits of Using Records
- Less Boilerplate:Reduces repetitive code for simple data holders.
- Immutability: Records are implicitly final and immutable, making them safer and easier to work with.
- Readability:
Clean syntax improves code readability.
Working with Records
Records can still have methods, but fields are always final. Let’s add a method to the `Person` record:
java
public record Person(String name, int age) {
public String greeting() {
return "Hello, " + name;
}
}
This simplicity and readability make records an excellent choice for lightweight data-carrying classes
2. Sealed Classes: Controlling Inheritance
What are Sealed Classes?
With inheritance, it’s sometimes essential to control which classes can extend a given class to prevent unintended hierarchies. Sealed Classes allow developers to specify a limited set of subclasses, restricting the ways a class can be extended.
Sealed Classes enable the "closed hierarchy" concept, where only a predefined set of classes can inherit from a base class. This is useful in domains like algebraic data types or protocols where specific subclasses should define the type structure.
Syntax of Sealed Classes
To define a Sealed Class, use the `sealed` keyword, followed by a `permits` clause listing the allowed subclasses:
java
public sealed class Shape permits Circle, Rectangle, Square {
// Class code
}
In this example, `Shape` can only be extended by `Circle`, `Rectangle`, and `Square`. If any other class tries to extend `Shape`, the code will not compile.
Types of Inheritance for Sealed Classes
The subclasses of a sealed class must adhere to one of the following inheritance options:
1. Final: The subclass cannot be further subclassed.
2. Non-Sealed:Allows further subclassing but within a controlled structure.
3. Sealed:The subclass itself can specify another level of permitted classes.
Here’s an example to illustrate this:
java
public sealed class Shape permits Circle, Rectangle {}
public final class Circle extends Shape {
// Final - no further subclassing
}
public non-sealed class Rectangle extends Shape {
// Allows further subclassing
}
Benefits of Sealed Classes
- Enhanced Type Safety:Ensures a restricted hierarchy of subclasses, improving predictability.
- Better Exhaustive Pattern Matching: Especially helpful in pattern matching expressions, where all possible subclasses are known.
- Clearer API Design:Provides control over how and where classes are extended.
3. Using Records and Sealed Classes Together
Records and Sealed Classes work well together, especially in cases where you need both concise data representation and controlled type hierarchies. Here’s an example:
public sealed interface Shape permits Circle, Rectangle {}
public record Circle(double radius) implements Shape {}
public record Rectangle(double length, double width) implements Shape {}
With this setup, `Shape` can only be represented by either `Circle` or `Rectangle` records. This approach is particularly useful in handling data within a controlled hierarchy while keeping the data classes lightweight.
4. Practical Use Cases for Records and Sealed Classes
- Data Transfer Objects (DTOs):Use records to create DTOs that are immutable and concise.
- Configuration Settings: Records are excellent for representing immutable configurations or settings.
- Finite Protocols and Workflows: Sealed classes work well for scenarios where a set of predefined states or responses is expected.
- Exhaustive Pattern Matching in Switch Statements: With sealed classes, you can use switch expressions to handle all possible subclasses of a type, making pattern matching safer and more predictable.
5. When to Use Records and Sealed Classes
| Use Case | Choose |
|------------------------------------|--------|
| Simple data holder, immutable | Record |
| Controlled inheritance structure |Sealed Class |
| Data classes within a limited set | Both |
How to obtain JAVA certification?
We are an Education Technology company providing certification training courses to accelerate careers of working professionals worldwide. We impart training through instructor-led classroom workshops, instructor-led live virtual training sessions, and self-paced e-learning courses.
We have successfully conducted training sessions in 108 countries across the globe and enabled thousands of working professionals to enhance the scope of their careers.
Our enterprise training portfolio includes in-demand and globally recognized certification training courses in Project Management, Quality Management, Business Analysis, IT Service Management, Agile and Scrum, Cyber Security, Data Science, and Emerging Technologies. Download our Enterprise Training Catalog from https://www.icertglobal.com/corporate-training-for-enterprises.php and https://www.icertglobal.com/index.php
Popular Courses include:
-
Project Management: PMP, CAPM ,PMI RMP
-
Quality Management: Six Sigma Black Belt ,Lean Six Sigma Green Belt, Lean Management, Minitab,CMMI
-
Business Analysis: CBAP, CCBA, ECBA
-
Agile Training: PMI-ACP , CSM , CSPO
-
Scrum Training: CSM
-
DevOps
-
Program Management: PgMP
-
Cloud Technology: Exin Cloud Computing
-
Citrix Client Adminisration: Citrix Cloud Administration
The 10 top-paying certifications to target in 2024 are:
Conclusion
Java’s Records and Sealed Classes offer significant improvements in managing data and inheritance in a clean, concise, and predictable way. By reducing boilerplate, improving immutability, and controlling subclassing, these features allow for more robust code with less effort.
As Java continues to introduce powerful features, Records and Sealed Classes stand out as fundamental tools for developers looking to create clean and manageable code structures. Embrace these new features to simplify your codebase and improve your Java applications’ readability and safety.
Contact Us For More Information:
Visit :www.icertglobal.com Email :
Comments (0)
Write a Comment
Your email address will not be published. Required fields are marked (*)