Unit 3 Java New Features
Unit 3 Java New Features
2
Functional Interfaces in Java
• A Functional Interface is an interface that has only one abstract method. They can have only one
functionality to exhibit. As a functional interface can have only one abstract method that’s why it is
also known as Single Abstract Method Interfaces (SAM) Interfaces.
• We can either create our own functional interface or can use predefined functional interfaces provided
by java.
• When we creating our own functional interface we should use @FunctionalInterface annotation to
mark it as functional interface. Although it is not mandatory to use it, but it’s good to use it with
functional interfaces to avoid addition of extra methods accidentally.
• It will throw compile time error if we try to add more than one abstract method in a functional
interface.
• Note that instances of functional interfaces can be created with the help of lambda expressions,
method references, constructor references, or anonymous classes.
• A functional interface can have any number of default
methods. Runnable, ActionListener, Consumer<T>, and Comparable<T> are some examples of
functional interfaces.
• A functional interface can also contain any number of static methods. 3
The following example interface contains one abstract method and one default method.
@FunctionalInterface
public interface ExampleInterface {
int randomCalculate(int a, int b);
4
Java Lambda Expressions
• Lambda expression is a new and important feature of Java which was included in Java SE 8.
• It provides a clear and concise way to represent one method interface using an expression.
• It is very useful in collection library. It helps to iterate, filter and extract data from collection.
• The Lambda expression is used to provide the implementation of an interface which has functional
interface. It saves a lot of code.
• In case of lambda expression, we don't need to define the method again for providing the
implementation. Here, we just write the implementation code.
• Java lambda expression is treated as a function.
Why use Lambda Expression
1. To provide the implementation of Functional interface.
2. Less coding.
Java Lambda Expression Syntax
(argument-list) -> {body}
5
Java lambda expression is consisted of three components.
1) Argument-list: It can be empty or non-empty as well.
2) Arrow-token: It is used to link arguments-list and body of expression.
3) Body: It contains expressions and statements for lambda expression.
No Parameter Syntax
() -> {
//Body of no parameter lambda
}
One Parameter Syntax
(p1) -> {
//Body of single parameter lambda
}
Two Parameter Syntax
(p1,p2) -> {
//Body of multiple parameter lambda
6
}
without lambda, Drawable implementation using anonymous class
interface Drawable{
public void draw();
}
public class Example1_LambdaExpression {
public static void main(String[] args) {
int width=10;
//without lambda, Drawable implementation using anonymous class
Drawable d=new Drawable(){
public void draw(){[Link]("Drawing "+width);}
};
[Link]();
}
7
}
A lambda expression can have zero or any number of arguments. examples:
8
Java Lambda Expression Example: No Parameter : with return
interface Sayable{
public String say();
}
public class Example3_LambdaExpression {
9
Java Lambda Expression Example: Single Parameter
interface Sayable1{
public String say(String name);
}
public class Example4_LambdaExpression{
public static void main(String[] args) {
// Lambda expression with single parameter.
Sayable1 s1=(name)->{
return "Hello!!, "+name;
};
[Link]([Link]("I m Good"));
// You can omit function parentheses
Sayable1 s2= name ->{
return "Hello, "+name;
};
[Link]([Link]("How r u??"));
}} 10
Java Lambda Expression Example: Multiple Parameters
interface Addable{
int add(int a,int b);
}
public class Example5_LambdaExpression{
public static void main(String[] args) {
// Multiple parameters in lambda expression
Addable ad1=(a,b)->(a+b);
[Link]([Link](10,20));
// Multiple parameters with data type in lambda expression
Addable ad2=(int a,int b)->(a+b);
[Link]([Link](100,200));
}
}
11
Java Lambda Expression Example: with or without return keyword
In Java lambda expression, if there is only one statement, you may or may not use return keyword.
You must use return keyword when lambda expression contains multiple statements.
interface Addable{
int add(int a,int b);
}
public class Example6_LambdaExpression {
public static void main(String[] args) {
// Lambda expression without return keyword.
Addable ad1=(a,b)->(a+b);
[Link]([Link](10,20));
// Lambda expression with return keyword.
Addable ad2=(int a,int b)->{
return (a+b);
};
[Link]([Link](100,200));
}
12
}
Java Lambda Expression Example: Multiple Statements
@FunctionalInterface
interface Sayable2{
String say(String message);
}
public class Example8_LambdaExpression{
public static void main(String[] args) {
// You can pass multiple statements in lambda expression
Sayable2 person = (message)-> {
String str1 = "I would like to say, ";
String str2 = str1 + message;
return str2;
};
[Link]([Link]("time is precious."));
}
}
13
Java Lambda Expression Example: Creating Thread
//You can use lambda expression to run thread
public class Example9_LambdaExpression{
public static void main(String[] args) {
//Thread Example without lambda
Runnable r1=new Runnable(){
public void run(){
[Link]("Thread1 is running...");
}
};
Thread t1=new Thread(r1);
[Link]();
//Thread Example with lambda
Runnable r2=()->{
[Link]("Thread2 is running...");
};
Thread t2=new Thread(r2);
[Link]();
}
14
}
Functionalities of Lambda Expression in Java
15
Java Method References
• Java provides a new feature called method reference in Java 8.
• Each time when you are using lambda expression to just referring a method, you can replace your
lambda expression with method reference.
3. Reference to a constructor.
16
1) Reference to a Static Method
You can refer to static method defined in the class.
Syntax : ContainingClass::staticMethodName
//In the following example, we have defined a functional interface and referring a static method
to it's functional method say().
interface Sayable3{
void say();
}
public class Example10_MethodReference {
public static void saySomething(){
[Link]("Hello, this is static method.");
}
public static void main(String[] args) {
// Referring static method
Sayable3 sayable = Example10_MethodReference::saySomething;
[Link](); // Calling interface method
}
} 17
2) Reference to an Instance Method
Like static methods, you can refer instance methods also.
Syntax: containingObject::instanceMethodName
//In the following example, we are referring non-static methods. You can refer methods by class object and
anonymous object.
interface Sayable4{
void say(); }
public class Ex11_InstanceMethodReference {
public void saySomething(){
[Link]("Hello, this is non-static method."); }
public static void main(String[] args) {
Ex11_InstanceMethodReference methodReference = new Ex11_InstanceMethodReference(); // Creating object
// Referring non-static method using reference
Sayable4 sayable = methodReference::saySomething;
// Calling interface method
[Link]();
// Referring non-static method using anonymous object
Sayable4 sayable2 = new Ex11_InstanceMethodReference()::saySomething; // You can use anonymous object also
// Calling interface method
[Link](); } } 18
3) Reference to a Constructor
You can refer a constructor by using the new keyword.
Syntax: ClassName::new
interface Messageable{
Message getMessage(String msg);
}
class Message{
Message(String msg){
[Link](msg);
}
}
public class Ex12_ConstructorReference {
public static void main(String[] args) {
Messageable hello=Message::new;
[Link]("Hello");
}
}
19
Base64 Encoding and Decoding in Java
• Base 64 is an encoding scheme that converts binary data into text format so that encoded textual data
can be easily transported over network un-corrupted and without any data loss.
• The Basic encoding means no line feeds are added to the output and the output is mapped to a set of
characters in A-Za-z0-9+/ character set and the decoder rejects any character outside of this set.
Encode simple String into Basic Base 64 format:
String BasicBase64format= [Link]().encodeToString(“actualString”.getBytes());
• In above code we called [Link] using getEncoder() and then get the encoded string by
passing the byte value of actualString in encodeToString() method as parameter.
Decode Basic Base 64 format to String
byte[] actualByte= [Link]().decode(encodedString);
String actualString= new String(actualByte);
• In above code we called [Link] using getDecoder() and then decoded the string passed in
decode() method as parameter then convert return value to string.
20
Java program to demonstrate Encoding simple String into Basic Base 64 format
import [Link].*;
public class Example13_Encoding {
public static void main(String[] args)
{
// create a sample String to encode
String sample = "India Team will win the Cup";
// print actual String
[Link]("Sample String:\n"+ sample);
// Encode into Base64 format
String BasicBase64format= [Link]().encodeToString([Link]());
// print encoded String
[Link]("Encoded String:\n"+ BasicBase64format);
}
}
21
Java program to demonstrate Decoding Basic Base 64 format to String
import [Link].*;
public class Example14_Decoding{
public static void main(String[] args)
{
// create an encoded String to decode
String encoded= "SW5kaWEgVGVhbSB3aWxsIHdpbiB0aGUgQ3Vw";
// print encoded String
[Link]("Encoded String:\n"+ encoded);
// decode into String from encoded format
byte[] actualByte = [Link]().decode(encoded);
String actualString = new String(actualByte);
URL encoding:
String encodedURL = [Link]().encodeToString(actualURL_String.getBytes());
• In above code we called [Link] using getUrlEncoder() and then get the encoded
URLstring by passing the byte value of actual URL in encodeToString() method as
parameter.
URL decoding:
byte[] decodedURLBytes = [Link]().decode(encodedURLString);
String actualURL= new String(decodedURLBytes);
• In above code we called [Link] using getUrlDecoder() and then decoded the URL
string passed in decode() method as parameter then convert return value to actual URL.
23
// Java program to demonstrate URL encoding using Base64 class
import [Link].*;
public class Example15_URLEncoding {
public static void main(String[] args)
{
// create a sample url String to encode
String sampleURL = "https:// [Link]";
• In Java, the Try-with-resources statement is a try statement that declares one or more
resources in it.
• A resource is an object that must be closed once your program is done using it.
• For example, a File resource or a Socket connection resource.
• The try-with-resources statement ensures that each resource is closed at the end of the
statement execution.
• If we don’t close the resources, it may constitute a resource leak and also the program could
exhaust the resources available to it.
• You can pass any object as a resource that implements [Link], which
includes all objects which implement [Link].
• By this, now we don’t need to add an extra finally block for just passing the closing
statements of the resources.
• The resources will be closed as soon as the try-catch block is executed.
29
Syntax: Try-with-resources
try(declare resources here)
{
// use resources
}
catch(FileNotFoundException e)
{
// exception handling
}
30
//Java Program for try-with-resources having single resource
import [Link].*;
class Ex20_TryWithResources {
public static void main(String[] args)
{
try(FileOutputStream fos= new FileOutputStream("F:\\[Link]")) // Adding resource
{
String text= "Hello World. This is my java program";
byte arr[] = [Link](); // Converting string to bytes
[Link](arr); // Text written in the file
}
// Catch block to handle exceptions
catch (Exception e) {
// Display message for the occurred exception
[Link](e);
}
// Display message for successful execution of program
[Link]("Resource are closed and message has been written into the F:\\[Link]");
}
} 31
//Java program for try-with-resources having multiple resources
import [Link].*;
class Ex21_TryWithResources {
public static void main(String[] args) {
//Writing data to a file using FileOutputStream by passing input file as a parameter
try (FileOutputStream fos= new FileOutputStream("F:\\[Link]");
//Adding resource // Reading the stream of character from
BufferedReader br = new BufferedReader(new FileReader("F:\\[Link]"))) {
//Declaring a string holding the stream content of the file
String text;
//Condition check using readLine() method which holds true till there is content in the input file
while ((text = [Link]()) != null) {
//Reading from input file passed above using getBytes() method
byte arr[] = [Link](); //String converted to bytes
[Link](arr); //Copying the content of passed input file to [Link]
}
//Display message when file is successfully copied
[Link]("File content copied to another one."); }
catch (Exception e) {
[Link](e); }
//Display message for successful execution of the program
[Link]("Resource are closed and message has been written into the [Link]");
}} 32
Annotations in Java
Java annotations are metadata (data about data) for our program source code. There are several predefined
annotations provided by the Java SE. Moreover, we can also create custom annotations as per our needs.
Annotations are used to provide supplemental information about a program.
• Annotations start with ‘@’.
• Annotations do not change the action of a compiled program.
• Annotations help to associate metadata (information) to the program elements i.e. instance variables,
constructors, methods, classes, etc.
• Annotations are not pure comments as they can change the way a program is treated by the compiler.
• Annotations basically are used to provide additional information, so could be an alternative to XML
and Java marker interfaces.
33
34
// Java Program to Demonstrate that Annotations are Not Barely Comments
class Base {
public void display() error: method does not override or implement
{ a method from a supertype
[Link]("Base display()");
} If we remove parameter (int x) or we
} remove @override, the program
public class Ex22_Derived extends Base { compiles fine.
// Overriding method as already up in above class Note: use compiler other than editor.
@Override public void display(int x)
{
[Link]("Derived display(int )");
}
public static void main(String args[])
{
Ex22_Derived obj = new Ex22_Derived();
[Link]();
}
}
35
Categories of Annotations
There are broadly 5 categories of annotations as listed:
[Link] Annotations
[Link] value Annotations
[Link] Annotations
[Link] Annotations
[Link] Annotations
1: Marker Annotations
The only purpose is to mark a declaration. These annotations contain no members and do not consist of any data. Thus, its
presence as an annotation is sufficient. Since the marker interface contains no members, simply determining whether it is
present or absent is sufficient. @Override is an example of Marker Annotation.
Example
@TestAnnotation()
2: Single value Annotations
These annotations contain only one member and allow a shorthand form of specifying the value of the member. We only
need to specify the value for that member when the annotation is applied and don’t need to specify the name of the member.
However, in order to use this shorthand, the name of the member must be a value.
Example
@TestAnnotation(“testing”);
3: Full Annotations
These annotations consist of multiple data members, names, values, pairs.
Example
@TestAnnotation(owner=”Rahul”, value=”Class Students”) 36
4: Type Annotations
• These annotations can be applied to any place where a type is being used.
• In early Java versions, you can apply annotations only to declarations. After releasing of Java SE 8 , annotations can be
applied to any type use.
• It means that annotations can be used anywhere you use a type. For example, if you want to avoid
NullPointerException in your code, you can declare a string variable like this: @NonNull String str;
Following are the examples of type annotations:
@NonNull List<String>
List<@NonNull String> str
Arrays<@NonNegative Integer> sort
@Encrypted File file
@Open Connection connection
void divideInteger(int a, int b) throws @ZeroDivisor ArithmeticException
• Note - Java created type annotations to support improved analysis of Java programs. It supports way of ensuring
stronger type checking.
37
// Java Program to Demonstrate Type Annotation
import [Link];
import [Link];
Note - Compiler will throw a compile-time error, if you apply the same annotation to a declaration without first
declaring it as repeatable.
40
Java Repeating Annotations Example
import [Link];
import [Link];
import [Link];
//Declaring repeatable annotation type
@Repeatable([Link])
@interface Game{
String name();
String day(); }
//Declaring container for repeatable annotation type
@Retention([Link])
@interface Games{
Game[] value(); }
//Repeating annotation
@Game(name = "Cricket", day = "Sunday")
@Game(name = "Hockey", day = "Friday")
@Game(name = "Football", day = "Saturday")
public class Example24_RepeatingAnnotations {
public static void main(String[] args) {
// Getting annotation by type into an array
Game[] game = Example24_RepeatingAnnotations.[Link]([Link]);
for (Game game2 : game) { // Iterating values
[Link]([Link]()+" on "+[Link]());
}}} 41
Predefined/ Standard Annotations
Java popularly defines seven built-in annotations as we have seen up in the hierarchy diagram.
• Four are imported from [Link]: @Retention, @Documented, @Target,
and @Inherited.
• Three are included in [Link]: @Deprecated, @Override and @SuppressWarnings
42
Java Anonymous Class
• In Java, a class can contain another class known as nested class.
• It's possible to create a nested class without giving any name.
• A nested class that doesn't have any name is known as an anonymous class.
• An anonymous class must be defined inside another class.
• Anonymous classes usually extend subclasses or implement interfaces.
• In anonymous classes, objects are created whenever they are required.
• Hence, it is also known as an anonymous inner class. Its syntax is:
class outerClass {
// defining anonymous class
object1 = new Type(parameterList)
{
// body of the anonymous class
};
}
43
Example 1: Anonymous Class Extending a Class
class Polygon {
public void display() {
[Link]("Inside the Polygon class");
}
}
class AnonymousDemo {
public void createClass() {
// creation of anonymous class extending class Polygon
Polygon p1 = new Polygon() {
public void display() {
[Link]("Inside an anonymous class.");
}
};
[Link]();
}
}
public class Main {
public static void main(String[] args) {
AnonymousDemo an = new AnonymousDemo();
[Link]();
}
44
}
Example 2: Anonymous Class Implementing an Interface
interface Polygon {
public void display();
}
class AnonymousDemo {
public void createClass() {
• When Diamond operator was introduced in Java 7, we can create the object without mentioning
generic type on right side of expression.
like: List<String> geeks = new ArrayList<>();
• With the help of Diamond operator, we can create an object without mentioning the generic type on
the right hand side of the expression. But the problem in JDK 7 is it will only work with normal
classes. Suppose you want to use the diamond operator for anonymous inner class then compiler will
46
throw error message.
Anonymous Inner Classes Example in Java 9
47
Local Variable Type Inference or LVTI in Java 10
What is type inference?
Type inference refers to the automatic detection of the datatype of a variable, done generally at the compiler time.
What is Local Variable type inference?
Local variable type inference is a feature in Java 10 that allows the developer to skip the type declaration associated with
local variables (those defined inside method definitions, initialization blocks, for-loops, and other blocks like if-else), and
the type is inferred by the JDK. It will, then, be the job of the compiler to figure out the datatype of the variable.
The compiler infers the type of the variable using the value provided. This type inference is restricted to local variables.
Old way of declaring local variable.
String name = "Welcome to [Link]";
New Way of declaring local variable.
var name = "Welcome to [Link]";
Now compiler infers the type of name variable as String by inspecting the value provided.
48
Points to Remember:
• No type inference in case of member variable, method parameters, return values.
• Local variable should be initialized at time of declaration otherwise compiler will not be infer and
will throw error.
• Local variable inference is available inside initialization block of loop statements.
• No runtime overhead. As compiler infers the type based on value provided, there is no performance
loss.
• No dynamic type change. Once type of local variable is inferred it cannot be changed.
49
How to declare local variables using LVTI:
// Java code for Normal local variable declaration
import [Link];
import [Link];
class A {
public static void main(String ap[])
{
List<Map> data = new ArrayList<>();
}
}
Can be re-written as:
// Java code for local variable
// declaration using LVTI
import [Link];
import [Link];
class A {
public static void main(String ap[])
{
var data = new ArrayList<>();
} 50
}
//Program shows the use of Local Variable Type Inference in JAVA 10.
import [Link];
52
Use Cases
53
Error cases:
Not permitted in class fields Not permitted for uninitialized local variables
// Sample java code to demonstrate // Sample java code to demonstrate
//that declaring class variables //that declaring uninitialized
//using 'var' is not permitted //local variables using 'var' produces an error
class A { class A {
var x; public static void main(String a[])
/* Error: class variables can't be declared {
using 'var'. Datatype needs to be explicitly var x;
mentioned*/ /* error: cannot use 'var' on variable without
} initializer*/
}
}
54
Error cases:
Not allowed as parameter for any Not permitted in method return type
methods // Java code to demonstrate
// Java code to demonstrate that // that a method return type
// var can't be used in case of // can't be 'var'
//any method parameters class A {
class A { public var show()
void show(var a) /* Error: Method return type can't be var*/
/*Error: can't use 'var' on method {
parameters*/ return 1;
{ }
} }
}
55
Error cases:
56
The Switch Construct
• The Switch Construct implements a multi-way branch that allows your program to be transferred to a
specific entry point in the code of the switch block, based on an input variable.
• There are two types of switch constructs in Java: the switch statement and the switch expression.
• Each of these constructs can be written in two ways: using the colon(:) notation and using
the arrow(->) notation.
• Java 12 introduced a new feature into the Java language called switch expressions, which can be used
to simplify many switch statements.
57
The Switch Statement With The Colon Notation (:)
class Example25 {
public static void main(String[] args) {
int value = 5;
switch (value){
case 1:
[Link]("Value is 1");
break;
case 2:
[Link]("Value is 2");
break;
case 5:
[Link]("Value is 5");
break;
default:
[Link]("Value doesn't match any of the constants");
}}} 58
The Switch Statement With The Arrow(->) Notation
class Example26
{
public static void main(String[] args)
{
int value = 5;
switch (value){
case 1 -> [Link]("Value is 1");
case 2, 3 -> [Link]("Value is 2"); //This is OK
case 5 -> [Link]("Value is 5");
default -> [Link]("Value doesn't match any of the constants");
}
}
} 59
You cannot use a group of statements in an arrow notation switch.
case 1 ->
[Link]("Value is 1");
[Link]("This line will not compile"); //Not allowed
case 2, 3 -> [Link]("Value is 2");
case 5 -> [Link]("Value is 5");
default -> [Link]("Value doesn't match any of the constants");
case 1 -> {
[Link]("Value is 1");
[Link]("This line will not compile");
} // allowed
case 2, 3 -> [Link]("Value is 2");
case 5 -> [Link]("Value is 5");
default -> [Link]("Value doesn't match any of the constants");
Note: Unlike the colon notation switch, there is no need for a break statement.
60
The Switch Expression
• A Switch expression has the same semantics as a switch statement, with the difference that it
returns a value.
• Just like switch statements, there are two forms of switch expressions: Colon notation and Arrow
notation switch expressions.
61
The Switch Expression With The Colon(:) Notation
The switch expression with the colon notation is analogous to the switch statement with the colon notation with the
difference that it returns a value (or throws an exception).
class Example27 {
public static void main(String[] args) {
int value = 5;
int switchValue = switch(value){
case 1:
[Link]("Value is 1");
yield 1;
case 2:
[Link]("Value is 2");
yield 2;
case 3,4:
[Link]("Value is 3 or 4");
yield 3;
default:
[Link]("Value not in range");
yield 0;
}; //Don't forget the semicolon (;)
[Link](switchValue); }} 62
The Switch Expression With The Arrow(->) Notation
The switch expression with arrow notation is simply a switch statement with the arrow notation that returns a
value(or throws an exception).
class Example28 {
public static void main(String[] args) {
int value = 3;
int switchValue = switch(value){
case 1 ->{
[Link]("Value is 1");
yield 1;
}
case 2-> 2;
case 3,4->{
[Link]("Value is 3 or 4");
yield 3;
}
default->
throw new IllegalArgumentException("Not a valid value");
};
[Link](switchValue);
63
}}
Points to Remember
The ‘yield’ and ‘return’ keywords in Java serve distinct purposes and are used in different contexts.
•A return statement returns control to the invoker of a method or constructor.
•A yield statement transfers control by causing an enclosing switch expression to produce a
specified value.
65
Text Blocks in Java
• Java 15 Text blocks feature is used to declare multi-line strings most efficiently.
• In earlier releases of the JDK, embedding multi-line code snippets required a tangled mess of explicit
line terminators, string concatenations, and delimiters.
• A text block is an alternative form of Java string representation that can be used anywhere a
traditional double-quoted string literal can be used.
• Text blocks begin with a """ (3 double-quote marks) observed through non-obligatory whitespaces
and a newline.
For example:
// Using a literal string
String text1 = “Dr. Surendra Kumar Keshari";
// Using a text block
String text2 = """
Dr. Surendra Kumar Keshari """;
66
Text Blocks Points to Remember
• The object created from text blocks is [Link] with the same properties as a regular string
enclosed in double quotes.
• A text block can be used in place of a string literal to improve the readability and clarity of the code.
• This primarily occurs when a string literal is used to represent a multi-line string.
• In this case there is considerable clutter from quotation marks, newline escapes, and concatenation
operators:
Note:
• A text block begins with three double-quote characters followed by a line terminator. You can't put a
text block on a single line, nor can the contents of the text block follow the three opening double-
quotes without an intervening line terminator.
• The reason for this is that text blocks are primarily designed to support multi-line strings, and
requiring the initial line terminator simplifies the indentation handling rules.
67
Text Blocks: Example
//Better String message
//Original String message
public class Main {
public class Main {
public static void main(String[] args) {
public static void main(String[] args) {
String message = """
String message = "Students:\n" +
Students:
"Roll Number 1:\n" +
Roll Number 1:
"Roll Number 2:\n" +
Roll Number 2:
"Roll Number 3:\n" +
Roll Number 3:
"Roll Number 4:\n" +
Roll Number 4:
"Roll Number 5:\n";
Roll Number 5. """;
[Link](message);
[Link](message);
}
}
}
}
68
Sealed Class in Java
• In programming, security and control flow are the two major concerns that must be considered
while developing an application.
• There are various controlling features such as the use of final and protected keyword restricts the
user to access variables and methods.
• In Java, we have the concept of abstract classes. It is mandatory to inherit from these classes since
objects of these classes cannot be instantiated.
• On the other hand, there is a concept of a final class in Java, which cannot be inherited or
extended by any other class.
• What if we want to restrict the number of classes that can inherit from a particular class? The
answer is sealed class.
• So, a sealed class is a technique that limits the number of classes that can inherit the given class.
• This means that only the classes designated by the programmer can inherit from that particular
class, thereby restricting access to it. when a class is declared sealed, the programmer must
specify the list of classes that can inherit it.
69
Sealed Class in Java
70
Sealed Class: Example
sealed class Students permits Student1, Student2, Student3 {
public void printName() {
[Link]("This is Students Class"); }}
non-sealed class Student1 extends Students {
public void printName() {
[Link]("My Name is Student1"); }}
non-sealed class Student2 extends Students {
public void printName() {
[Link]("My Name is Student2"); }}
final class Student3 extends Students {
public void printName() {
[Link]("My Name is Student3"); }}
public class Main {
public static void main(String[] args) {
Students s = new Students();
Students s1 = new Student1();
Students s2 = new Student2();
Students s3 = new Student3();
[Link]();
[Link]();
[Link]();
71
[Link](); }}
Record Class in Java
• Record classes, which are a special kind of class, help to model plain data aggregates with less
ceremony than normal classes.
• In Java, a record is a special type of class declaration aimed at reducing the boilerplate code.
• Java records were introduced with the intention to be used as a fast way to create data carrier classes,
i.e. the classes whose objective is to simply contain data and carry it between modules, also known as
POJOs (Plain Old Java Objects) and DTOs (Data Transfer Objects).
• Record was introduced in Java SE 14 as a preview feature.
72
Simple Example: Record in Java
//Java Program to Illustrate Record's functionalities
class RecordExample {
public record Employee(int id, String firstName, String lastName)
{
}
//Main driver method
public static void main(String args[]) {
74
//Java Program Illustrating a Record class //defining constructors, instance methods //and static fields
public record Employee(int id, String firstName, String lastName) { //Record class
// Instance fields need to be present in the record’s parameters but record can define static fields.
static int empToken;
// Constructor 1 of this class // Compact Constructor
public Employee {
if (id < 100) {
throw new IllegalArgumentException("Employee Id cannot be below 100.");
}
if ([Link]() < 2) {
throw new IllegalArgumentException("First name must be 2 characters or more.");
} }
// Constructor 2 of this class // Alternative Constructor
public Employee(int id, String firstName) {
this(id, firstName, null); }
public void getFullName() { // Instance methods
if (lastName == null)
[Link](firstName());
else
[Link](firstName() + " "+ lastName());
}
public static int generateEmployeeToken() { // Static methods
return ++empToken; 75
//Java Program to Illustrate Record's functionalities
class EmpMainClass {
//Main driver method
public static void main(String args[]) {
// Creating object with default constructor
Employee e1 = new Employee(1001, "Derok", "Dranf");