0% found this document useful (0 votes)
1 views27 pages

java-unit-iii-oops-with-java-unit-3-notes

The document covers Object-Oriented Programming (OOP) concepts in Java, focusing on functional interfaces, lambda expressions, method references, and the Stream API. It explains the use of annotations, default and static methods in interfaces, and provides examples of lambda expressions and method references. Additionally, it discusses Base64 encoding and decoding in Java, including practical examples for encoding and decoding strings and byte arrays.

Uploaded by

Apeksha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
1 views27 pages

java-unit-iii-oops-with-java-unit-3-notes

The document covers Object-Oriented Programming (OOP) concepts in Java, focusing on functional interfaces, lambda expressions, method references, and the Stream API. It explains the use of annotations, default and static methods in interfaces, and provides examples of lambda expressions and method references. Additionally, it discusses Base64 encoding and decoding in Java, including practical examples for encoding and decoding strings and byte arrays.

Uploaded by

Apeksha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 27

lOMoARcPSD|21983112

Java Unit III - Oops with java unit 3 notes

oops with java (Dr. A.P.J. Abdul Kalam Technical University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Apeksha (er.apeksha2015@gmail.com)
lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

UNIT-III

Functional Interface:-

1. An interface with only one abstract method is called functional interface.


2. To make sure that an interface contains only one abstract method, @FunctionalInterface
annotation is used.

For Example:-

@FunctionalInterface
Interface Sayable{
public void saySomething(String msg);
}
class Doable implements Sayable
{
@Override
public void saySomething(String msg)
{
System.out.println(msg);
}
}
class TestFI
{
public static void main(String …s)
{
Doable obj=new Doable();
Obj.saySomething(“United”);
}
}

Note:
1. It is not mandatory to use @FunctionalInterface or @Override annotation to define
a functional interface.
2. Functional Interface can also contains methods from Object class like
hashCode(),toString() etc.
3. Functional Interface cannot contain user-define non-abstract method.

Static method and default method within an interface:-

1. From java version 9, an interface can contain default methods as well as static methods.
2. Default method is a method with body(instructions). It is defined using “default” keyword.
3. Static method is a method defined with “static” keyword (just like in a class).

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

For example:-
Interface Vehicle
{
public void ignition();
public void accelerate();
public void brakes();
public void gearUp();
public void gearDown();
public applyClutch();
public releaseClutch();
public default String systemDiagnostics()
{
return “System diagnosis is in progress…”;
}
public static int getHorsePower(int rpm,int torque)
{
return ((rpm*torque)/5252);
}
}

class Car implements Vehicle


{
int rpm,torque,speed;
public Car(int t,int,r,int s)
{
rpm=r;
seed=s;
torque=t;
}
public void ignition(){
System.out.println(“Engine started”);
}
public void accelerate(){
System.out.println(“Car accelerated”);
}
public void brakes(){
System.out.println(“Car stopped”);
}
public void gearUp(){
System.out.println(“gear is shifted Up”);
}
public void gearDown(){
System.out.println(“gear is shifted Down”);
}
public applyClutch(){
System.out.println(“Clutch is down”);
}
public releaseClutch(){

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

System.out.println(“Clutch is released”);
}

}
Class Test
{
Car swift=new Car(10,2000,20);
Car nexon=new Car(11,6000,60);
Swift.systemDiagnosis();
Nexon.systemDiagnosis();
Vehicle.getHorsePower(swift.rpm,swift.torque);
Vehicle.getHorsePower(nexon.rpm,nexon.torque);

Explanation: In the above program, a Vehicle interface is defined with some abstract
methods, default method and static method. Since every Car have its own operating mechanism like
transmission system, etc so they are defined as abstract so every car defines its own implementation
but it may be possible that car diagnosis system is same so it is defined using “default” keyword so
every car need not to give its own implementation. Similarly, a utility task of fetching car’s horse
power is defined as static method. Any car can use this utility function as they need.

Lambda Expression:-
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, so compiler does not create


.class file.

Java Lambda Expression Syntax


(argument-list) -> {body}

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.

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

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
}

Example 1:-
@FunctionalInterface //It is optional
interface Drawable{
public void draw();
}

public class LambdaExpressionExample2 {


public static void main(String[] args) {
int width=10;

//with lambda
Drawable d2=()->{
System.out.println("Drawing "+width);
};
d2.draw();
}
}

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

Example 2:
interface Sayable{
public String say(String name);
}

public class LambdaExpressionExample4{


public static void main(String[] args) {

// Lambda expression with single parameter.


Sayable s1=(name)->{
return "Hello, "+name;
};
System.out.println(s1.say("Sonoo"));

// You can omit function parentheses


Sayable s2= name ->{
return "Hello, "+name;
};
System.out.println(s2.say("Sonoo"));
}
}

Method Reference:-
Method reference is used to refer method of functional interface. It is compact
and easy form of lambda expression. Each time when you are using lambda
expression to just referring a method, you can replace your lambda expression
with method reference.

Types of Method References

There are following types of method references in java:

1. Reference to a static method.


interface Sayable{
void say();
}
public class MethodReference {

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

public static void saySomething(){


System.out.println("Hello, this is static method.");
}
public static void main(String[] args) {
// Referring static method
Sayable sayable = MethodReference::saySomething;
// Calling interface method
sayable.say();
}
}
2. Reference to an instance method.
interface Sayable{
void say();
}
public class InstanceMethodReference {
public void saySomething(){
System.out.println("Hello, this is non-static method.");
}
public static void main(String[] args) {
InstanceMethodReference methodReference = new
InstanceMethodReference(); // Creating object
// Referring non-static method using reference
Sayable sayable = methodReference::saySomething;
// Calling interface method
sayable.say();
// Referring non-static method using anonymous object
Sayable sayable2 = new
InstanceMethodReference()::saySomething; // You can use anonymous
object also
// Calling interface method
sayable2.say();
}
}
3. Reference to a constructor.
interface Messageable{
Message getMessage(String msg);
}

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

class Message{
Message(String msg){
System.out.print(msg);
}
}
public class ConstructorReference {
public static void main(String[] args) {
Messageable hello = Message::new;
hello.getMessage("Hello");
}
}

Stream API

Stream API is used to process collections of objects. A stream in Java is a


sequence of objects that supports various methods which can be pipelined to
produce the desired result.

Use of Stream in Java


There uses of Stream in Java are mentioned below:

1. Stream API is a way to express and process collections of objects.


2. Enable us to perform operations like filtering, mapping,reducing and
sorting.

Java Stream Features


The features of Java stream are mentioned below:

• A stream is not a data structure instead it takes input from the


Collections, Arrays or I/O channels.
• Streams don’t change the original data structure, they only provide the
result as per the pipelined methods.
• Each intermediate operation is lazily executed and returns a stream as a
result, hence various intermediate operations can be pipelined. Terminal
operations mark the end of the stream and return the result.

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

Different Operations On Streams


There are two types of Operations in Streams:

• Intermediate Operations
• Terminate Operations

Benefit of Java Stream


There are some benefits because of which we use Stream in Java as mentioned
below:

1. No Storage
2. Pipeline of Functions
3. Laziness
4. Can be infinite
5. Can be parallelized
6. Can be created from collections, arrays, Files Lines, Methods in Stream,
IntStream etc.

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

Important Intermediate Operations


There are a few Intermediate Operations mentioned below:

1. map()
The map method is used to return a stream consisting of the results of
applying the given function to the elements of this stream.

List number = Arrays.asList(2,3,4,5);


List square = number.stream().map(x->x*x).collect(Collectors.toList());

2. filter()
The filter method is used to select elements as per the Predicate passed as an
argument.

List names = Arrays.asList("Reflection","Collection","Stream");


List result = names.stream().filter(s>s.startsWith("S")).collect(Collectors.toList());

3. sorted()
The sorted method is used to sort the stream.

List names = Arrays.asList("Reflection","Collection","Stream");


List result = names.stream().sorted().collect(Collectors.toList());

Terminal Operations
Terminal Operations are the type of Operations that return the result. These
Operations are not processed further just return a final result value.

Important Terminal Operations


There are a few Terminal Operations mentioned below:

1. collect()
The collect method is used to return the result of the intermediate operations
performed on the stream.

List number = Arrays.asList(2,3,4,5,3);


Set square = number.stream().map(x->x*x).collect(Collectors.toSet());

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

2. forEach()
The forEach method is used to iterate through every element of the stream.

List number = Arrays.asList(2,3,4,5);


number.stream().map(x->x*x).forEach(y->System.out.println(y));

3. reduce()
The reduce method is used to reduce the elements of a stream to a single
value. The reduce method takes a BinaryOperator as a parameter.

List number = Arrays.asList(2,3,4,5);


int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);
Here ans variable is assigned 0 as the initial value and i is added to it.

Note: Intermediate Operations are running based on the concept of Lazy


Evaluation, which ensures that every method returns a fixed value(Terminal
operation) before moving to the next method.

Base64 Encode and Decode:

Base64 encoding allows encoding binary data as text strings for safe transport,
at the cost of larger data size. It is commonly used when there is a need to
encode binary data that needs to be stored or transferred via media that are
designed to deal with textual data (like transporting images inside an XML,
JSON document, etc.).

How to Convert a String to Base64 Encoded String in Java?


In Java, the java.util.Base64 class provides static methods to encode and
decode between binary and base64 formats. The encode() and decode()
methods are used.

Base64 class provides three different encoders and decoders to encrypt


information at each level. You can use these methods at the following levels.

1. Basic Encoding and Decoding


2. URL and Filename Encoding and Decoding
3. MIME

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

Nested Classes of Base64


Class Description
Base64.Decoder This class implements a decoder for decoding
byte data using the Base64 encoding scheme as
specified in RFC 4648 and RFC 2045.
Base64.Encoder This class implements an encoder for encoding
byte data using the Base64 encoding scheme as
specified in RFC 4648 and RFC 2045.

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

Java Base64 Example: Basic Encoding and Decoding


import java.util.Base64;
public class Base64BasicEncryptionExample {
public static void main(String[] args) {
// Getting encoder
Base64.Encoder encoder = Base64.getEncoder();
// Creating byte array
bytebyteArr[] = {1,2};
// encoding byte array
bytebyteArr2[] = encoder.encode(byteArr);
System.out.println("Encoded byte array: "+byteArr2);
bytebyteArr3[] = newbyte[5]; // Make sure it has enough size to store
copied bytes
intx = encoder.encode(byteArr,byteArr3); // Returns number of bytes written
System.out.println("Encoded byte array written to another array: "+byteArr3);
System.out.println("Number of bytes written: "+x);

// Encoding string
String str = encoder.encodeToString("UNITED".getBytes());
System.out.println("Encoded string: "+str);
// Getting decoder
Base64.Decoder decoder = Base64.getDecoder();
// Decoding string
String dStr = new String(decoder.decode(str));
System.out.println("Decoded string: "+dStr);
}
}
Output:

Encoded byte array: [B@6bc7c054


Encoded byte array written to another array: [B@232204a1
Number of bytes written: 4
Encoded string: SmF2YVRwb2ludA==
Decoded string: UNITED

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

Java Base64 Example: URL Encoding and Decoding


import java.util.Base64;
publicclass Base64BasicEncryptionExample {
publicstaticvoid main(String[] args) {
// Getting encoder
Base64.Encoder encoder = Base64.getUrlEncoder();
// Encoding URL
String eStr = encoder.encodeToString("http://www.united.ac.in/summer-
training/".getBytes());
System.out.println("Encoded URL: "+eStr);
// Getting decoder
Base64.Decoder decoder = Base64.getUrlDecoder();
// Decoding URl
String dStr = new String(decoder.decode(eStr));
System.out.println("Decoded URL: "+dStr);
}
}

Output:

Encoded URL: R0cDovL3d3dy5qYXZhdHBvaW50LmNvbS9qYXZhLXR1dG9yaWFsLw==


Decoded URL: http:// united.ac.in/summer-training /

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

The try-with-resources statement


In Java, the try-with-resources statement is a try statement that declares one or
more resources. The resource is as an object that must be closed after finishing the
program. The try-with-resources statement ensures that each resource is closed at
the end of the statement execution.

You can pass any object that implements java.lang.AutoCloseable, which includes all
objects which implement java.io.Closeable.

The following example writes a string into a file. It uses an instance of


FileOutputStream to write data into the file. FileOutputStream is a resource that
must be closed after the program is finished with it. So, in this example, closing of
resource is done by itself try.

Try-with-resources Example 1
import java.io.FileOutputStream;
public class TryWithResources {
public static void main(String args[]){
// Using try-with-resources
try(FileOutputStream fileOutputStream =newFileOutputStream("/java7-new-
features/src/abc.txt")){
String msg = "Welcome to United!";
byte byteArray[] = msg.getBytes(); //converting string into byte array
fileOutputStream.write(byteArray);
System.out.println("Message written to file successfuly!");
}catch(Exception exception){
System.out.println(exception);
}
}
}
Output:

Message written to file successfuly!


Output of file

Welcome to United!

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

Java Module System


Java Module System is a major change in Java 9 version. Java added this feature to
collect Java packages and code into a single unit called module.

Module is a collection of Java programs or softwares. To describe a module, a Java


file module-info.java is required. This file also known as module descriptor and
defines the following

• Module name
• What does it export
• What does it require

How to Create a module in java?


Earlier we supposed that our java module name is org.geeksforgeeks which has
followed the reverse domain pattern to overcome the naming conflicts.

Creating the java modules involves three steps to be created in java. The three
steps to be followed are:

• We want to create a directory structure.


• We want to create a module declarator as we mentioned earlier which is
used to describe the module. {module-info.java}
• we have to create a source code in that module

Local Variable Type Inference


Type inference refers to the automatic detection of the datatype of a variable,
done generally at the compiler time.

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.

// Java code for local variable


// declaration using LVTI

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

import java.util.ArrayList;
import java.util.List;
class A {
public static void main(String ap[])
{
var data = new ArrayList<>();
}
}

Switch Expressions and Yield Keyword:

Upgraded Switch in Java 13.

1. Supports multiple values per case:

switch (itemCode) {
case 001, 002, 003 :
System.out.println("It's an electronic gadget!");
break;

case 004, 005:


System.out.println("It's a mechanical device!");
}
2. yield is used to return a value:

int val = switch (code) {


case "x", "y" :
yield 1;
case "z", "w" :
yield 2;
};

3. Switch can be used as an expression:


String text = switch (itemCode) {
case 001 :
yield "It's a laptop!";
case 002 :

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

yield "It's a desktop!";


case 003 :
yield "It's a mobile phone!";
default :
throw new IllegalArgumentException(itemCode + "is an
unknown device!");
};

4. Necessary to return value/exception:


switch expression should always return some value or explicitly
throw an exception.
5. Switch with arrows:
The new arrow ⇾ syntax has been introduced for the switch. It
can be used with the switch as an expression as well as a
statement. The statements on the right side of an ⇾ are executed
if an exact case matches on the left side.

On the right side of ⇾ we can have any of the following –

• Statement / expression
• throw statement
• {} block

The main advantage of this syntax is that we don’t need a break statement to
avoid the default fall-through. So, the rule is, if we need fall-through, use case:
else if not use case ⇾. Also note, for all case branches it should be either case:
or case ⇾. It cannot be different or different cases in a switch else it results in
an error.

switch (itemCode) {
case 001 -> System.out.println("It's a laptop!");
case 002 -> System.out.println("It's a desktop!");
case 003,004 -> System.out.println("It's a mobile phone!");
}

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

6. Scope: The variables declared in the traditional switch exists until the
end of the switch statement. If we want the variables to have a case
level scope, we can use {} introduced by the enhanced switch in Java 13.

switch (errorCode) {
case 101: {
// This variable exists just in this {} block
int num = 200;
break;
}
case 300: {
// This is ok, {} block has a separate scope
int num = 300;
}
}

Text Block in java

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 = "United Group of Institution";

// Using a text block


String text2 = """
United Group of Institution """;

The object created from text blocks is java.lang.String with the same
properties as a regular string enclosed in double quotes.

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

Records in java
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).

Case Scenario: Consider a simple class Employee, whose objective is to


contain an employee’s data such as its ID and name and act as a data
carrier to be transferred across modules. To create such a simple class,
you’d need to define its constructor, getter, and setter methods, and if
you want to use the object with data structures like HashMap or print
the contents of its objects as a string, we would need to override
methods such as equals(), hashCode(), and toString().

// Java Program Illustrating Program Without usage of


// Records

// A sample Employee class


class Employee {

// Member variables of this class


private String firstName;
private String lastName;
private int Id;

// Constructor of this class


public Employee(String firstName, String lastName,
int Id)
{

// This keyword refers to current instance itself


this.firstName = firstName;
this.lastName = lastName;
this.Id = Id;
}

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

// Setter and Getter methods

// Setter-getter Method 1
public void setFirstName(String firstName)
{
this.firstName = firstName;
}

// Setter-getter Method 2
// to get the first name of employee
public String getFirstName() { return firstName; }

// Setter-getter Method 3
// To set the last name of employees
public void setLastName(String lasstName)
{

// This keyword refers to current object itself


this.lastName = lastName;
}

// Setter-getter Method 3
// To set the last name of employees
public String getLastName() { return lastName; }

// Setter-getter Method 4
// To set the last name of employees
public void setId(int Id) { this.Id = Id; }

// Setter-getter Method 5
// To set the last name of employees
public int getId() { return Id; }

// Setter-getter Method 6
public String toString()
{

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

// Return the attributes


return "Employee [firstName=" + firstName
+ ", lastName=" + lastName + ", Id=" + Id + "]";
}

// Method 7
// Overriding hashCode method
@Override public int hashCode()
{

// Final variable
final int prime = 31;
int result = 1;

result = prime * result + Id;


result = prime * result
+ ((firstName == null)
?0
: firstName.hashCode());
result
= prime * result
+ ((lastName == null) ? 0
:
lastName.hashCode());

return result;
}

// Method 8
// Overriding equals method to
// implement with data structures
@Override public boolean equals(Object obj)
{

// This refers to current instance itself


if (this == obj)

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

return true;

if (obj == null)
return false;

if (getClass() != obj.getClass())
return false;

Employee other = (Employee)obj;

if (Id != other.Id)
return false;

if (firstName == null) {
if (other.firstName != null)
return false;
}

else if (!firstName.equals(other.firstName))
return false;

if (lastName == null) {
if (other.lastName != null)
return false;
}
else if (!lastName.equals(other.lastName))
return false;

return true;
}
}
Now let’s look at what it would take to create a similar class using
Record.

public record Employee(int id, String firstName, String lastName) {}

That’s it!

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

Sealed Class in Java

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. The concept of sealed
classes in Java was introduced in Java 15.

sealed class Human permits Manish, Vartika, Anjali


{
public void printName()
{
System.out.println("Default");
}
}
non-sealed class Manish extends Human
{
public void printName()
{
System.out.println("Manish Sharma");
}
}
sealed class Vartika extends Human
{
public void printName()
{
System.out.println("Vartika Dadheech");
}
}
final class Anjali extends Human
{
public void printName()
{
System.out.println("Anjali Sharma");
}
}

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

Explanation of the above Example:


• Human is the parent class of Manish, Vartika, and Anjali. It is a sealed
class so; other classes cannot inherit it.
• Manish, Vartika, and Anjali are child classes of the Human class, and it
is necessary to make them either sealed, non-sealed, or final. Child
classes of a sealed class must be sealed, non-sealed, or final.
• If any class other than Manish, Vartika, and Anjali tries to inherit from
the Human class, it will cause a compiler error.

Java Type and Repeating Annotations

Java Type Annotations


Java 8 has included two new features repeating and type annotations in its
prior annotations topic. 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

Java Repeating Annotations


In Java 8 release, Java allows you to repeating annotations in your source code.
It is helpful when you want to reuse annotation for the same class. You can
repeat an annotation anywhere that you would use a standard annotation.

For compatibility reasons, repeating annotations are stored in a container


annotation that is automatically generated by the Java compiler. In order for
the compiler to do this, two declarations are required in your code.

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)


lOMoARcPSD|21983112

Object Oriented Programming with Java [BCS 403]

Java Repeating Annotations Example


// Importing required packages for repeating annotation
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
// Declaring repeatable annotation type
@Repeatable(Games.class)
@interfaceGame{
String name();
String day();
}
// Declaring container for repeatable annotation type
@Retention(RetentionPolicy.RUNTIME)
@interfaceGames{
Game[] value();
}
// Repeating annotation
@Game(name = "Cricket", day = "Sunday")
@Game(name = "Hockey", day = "Friday")
@Game(name = "Football", day = "Saturday")
public class RepeatingAnnotationsExample {
public static void main(String[] args) {
// Getting annotation by type into an array
Game[] game =
RepeatingAnnotationsExample.class.getAnnotationsByType(Game.class);
for (Gamegame2 : game) { // Iterating values
System.out.println(game2.name()+" on "+game2.day());
}
}
}
OUTPUT:

Cricket on Sunday
Hockey on Friday
Football on Saturday

DHANANJAYSHARMAOFFICIALS

Downloaded by Apeksha (er.apeksha2015@gmail.com)

You might also like