OOPs Unit 3 Notes
OOPs Unit 3 Notes
Unit: - 3
Java New Features
Abstract Methods
An abstract method in Java is a method declared without a
body (i.e., no implementation). It only defines the method
signature and must be implemented by subclasses.
The class containing the abstract method must be abstract.
Abstract methods act like placeholders for methods that must
be implemented in the child classes.
Syntax
abstract class Animal {
abstract void makeSound(); // abstract method
}
Interfaces in Java
Syntax
interface Vehicle {
void start(); // abstract method
}
Functional Interfaces
A functional interface in Java is an interface that contains
exactly one abstract method.
These interfaces are used primarily in lambda
expressions and method references, enabling more
concise and readable code, especially for functional-
style programming introduced in Java 8.
Key Characteristics
Has exactly one abstract method.
Can have default and static methods.
Annotated with @FunctionalInterface (optional but
recommended).
Used with lambda expressions, method references, and
streams API.
Example
@FunctionalInterface
interface MyFunction {
void execute();
}
Syntax
ClassName::methodName
@FunctionalInterface
interface Calculator {
int compute(int a, int b);
}
class MathOperations {
static int add(int x, int y) {
return x + y;
}
}
class Printer {
void print(String msg) {
System.out.println(msg);
}
}
4. Reference to a Constructor
@FunctionalInterface
interface PersonFactory {
Person create(String name);
}
class Person {
String name;
Person(String name) {
this.name = name;
}
}
Stream API
What is a Stream?
A Stream is a sequence of elements that supports
various operations to process data:
It does not store data itself.
It is not a data structure (like List or Set).
It works with Collections, arrays, or I/O channels.
Syntax
interface Vehicle {
default void start() {
System.out.println("Vehicle is starting");
}
}
interface Vehicle {
static void fuelType() {
System.out.println("Petrol or Diesel");
}
}
Base64
Base64 is used to encode binary data (like images or files)
into a text string made up of ASCII characters. It's especially
useful when transmitting data over media that are designed
to deal with text (like JSON, XML, or HTML).
import java.util.Base64;
// Encode
String encoded =
Base64.getEncoder().encodeToString(original.getBytes())
;
System.out.println("Encoded: " + encoded);
// Decode
byte[] decodedBytes =
Base64.getDecoder().decode(encoded);
String decoded = new String(decodedBytes);
System.out.println("Decoded: " + decoded);
}
}
Features of Try-With-Resources
Feature Description
Automatic closing No need for finally to close
resources.
Supports multiple Declare multiple resources
resources. in try().
Cleaner Syntax Less boilerplate code
Exception Suppression. Handles exceptions
through during both try
and close.
Type Annotations
Repeating Annotations
Repeating annotations in Java, introduced in Java 8 through
JSR 308, allow developers to apply the same annotation more
than once to a single program element such as a class,
method, or field.
Advantages
1. Modularization
2. Encapsulation
3. Improved Performance
4. Isolation and Security
5. Scalability
Diamond Syntax
Example: -
interface Person{
void show();
}
interface Person{
void show();
}
public class AnonymousEx {
public static void main(String args[])
{
Person p = Person(){
Public void show(){
System.out.println(“show”);
}
};
Example in Java:
// Before Java 10
String message = "Hello, World!";
int count = 10;
// With local variable type inference (Java 10+)
var message = "Hello, World!";
var count = 10;
2. Improves maintainability:
o If you change the right-hand side type, you don’t
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
Key Points:
break prevents fall-through to the next case.
default is optional and executed when no case matches.
Works with int, char, enum, String (since Java 7), etc.
Switch Expression
A switch expression enhances the traditional switch
statement by:
Allowing it to return a value.
Using arrow (->) syntax to avoid fall-through.
Being more concise and readable.
Syntax:
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Invalid day";
};
System.out.println(dayName);
Features:
No need for break.
Returns a value (assignable to a variable).
Allows block bodies with yield:
Example:
int day = 2;
String dayType = switch (day) {
case 1, 7 -> "Weekend";
case 2, 3, 4, 5, 6 -> {
System.out.println("Weekday logic here");
yield "Weekday";
}
default -> "Invalid day";
};
System.out.println(dayType);
Improved Readability
Less Escaping
Automatic Formatting
Easier Maintenance
Records in Java
Syntax of a Record
1. Concise Syntax
Records provide a concise syntax for declaring classes
that the primarily used to hold data.
2. Implicit Finality
By default all components of a record are implicitly final.
This ensures that instances if the record are immutable.
3. Compact Initialization
Records generate a compact constructor to initialize the
record’s components. This allows you to create instances
of the record using a concise syntax.
Benefit Explanation
Explicit control Only the classes you list in
permits can extend your
sealed class.
Improved reasoning When you use sealed
classes in pattern
matching or switch
expressions, the compiler
can check for
exhaustiveness —
meaning you handled all
permitted types.
Better encapsulation Limits the number of
subclasses, helping keep
the code predictable and
maintainable.
Useful with pattern Works well with instanceof
matching and future enhancements
in pattern matching for
deconstructing types.