Static block ,static methods and static fields
Defination :
A static block in Java is used to initialize static variables. It gets executed once when the
class is loaded into memory, before the main() method or any object of the class is created.
🔹 Key Points:
● A class can have multiple static blocks.
● Static blocks are executed in the order they appear in the class.
● Used commonly for initializing static data, especially when the initialization is complex
and can't be done in a single line.
public class StaticBlockExample
{
static int number;
static {
[Link]("Static block executed.");
number = 100;
}
public static void main(String[] args) {
[Link]("Main method executed.");
[Link]("Value of number: " + number);
}
}
✅ Static Field and Static Method in Java
In Java, the static keyword is used to indicate that a field or method belongs to the class
rather than instances (objects) of the class.
🔹 1. Static Field (Variable)
● A static field is shared by all objects of the class.
● It is initialized only once when the class is loaded.
● It is accessed using the class name, or through an object (not recommended).
🔹 2. Static Method
● A static method belongs to the class, not to any object.
● It can access only static data (not instance variables unless an object is used).
● It can be called using the class name (recommended).
public class Employee {
// static fields
static String companyName = "TCS";
// Instance fields
int empId;
String empName;
Employee(int id, String name)
{
empId = id;
empName = name;
}
// Instance method
void display() {
[Link]("Employee ID: " + empId);
[Link]("Employee Name: " + empName);
[Link]("Company: " + companyName);
}
// Static method
static void changeCompany(String newCompany) {
companyName = newCompany;
[Link]("Company name changed to: " + companyName);
}
public static void main(String[] args)
{
// Accessing static method
[Link]("Infosys");
// Creating objects
Employee e1 = new Employee(101, "Neha");
Employee e2 = new Employee(102, "Amit");
[Link]();
[Link]("-----");
[Link]();
}
}
—--------------------------------------------------------------------------------------------------------------------------
class Account
{
int accountNo;
double balance;
static double rate = 0.05; // Static field shared by all accounts
void setData(int n, double bal) {
accountNo = n;
balance = bal;
}
// Method to calculate quarterly interest
void quarterRateCal() {
double interest = balance * rate * 0.25;
balance += interest;
}
// Static method to modify interest rate
static void modifyRate(double incr) {
rate += incr;
[Link]("Modified rate of Interest: " + rate);
}
// Method to display account information
void show() {
[Link]("Account Number: " + accountNo);
[Link]("Rate of Interest: " + rate);
[Link]("Balance: ₹" + balance);
}
public static void main(String[] args) {
Account acc1 = new Account();
Account acc2 = new Account();
// Modify the static interest rate
[Link](0.01); // Now rate becomes 0.06
[Link]("\nCustomer 1 Information:");
[Link](201, 1000);
[Link]();
[Link]();
[Link]("\nCustomer 2 Information:");
[Link](202, 1500);
[Link]();
[Link]();
}
}
—----------------------------------------------------------------------------------------------------------------------------
✅ What are Predefined Classes in Java?
Predefined classes in Java are built-in classes provided by the Java Standard Library
(JDK) to help developers perform common tasks without having to write code from scratch.
These classes are already defined by Java and organized into packages such as [Link],
[Link], [Link], etc.
Package Class Name Purpose
[Link] String For text and string operations
math For mathematical functions
Object Parent class of all classes
Integer, Double For wrapper classes
(primitive to object)
[Link] Scanner For input from keyboard
ArrayList Resizable array
Date, Calendar Date and time manipulation
[Link] File, BufferedReade File handling
[Link] / [Link] Button, JFrame GUI development
✅ Object Class in Java
The Object class in Java is the superclass of all classes. Every class in Java implicitly
extends the Object class unless it extends another class explicitly.
🧾 Key Methods of the Object Class
toString() Returns a string representation of the object
equals(Object obj) Compares two objects for equality
hashCode() Returns an integer hash code for the object
getClass() Returns the runtime class of the object
clone() Creates a copy of the object (shallow copy)
finalize() Called by garbage collector before
destruction
wait(), notify(), notifyAll() Used for thread synchronization
—----------------------------------------------------------------------------------------------------------------------------
class Rectangle extends Object
{
private double length,breadth;
Rectangle(double x , double y)
{
length = x ;
breadth = y;
}
public void area()
{
[Link]("Area of Rectangle is = "+(length * breadth));
}
public void circumferrance()
{
[Link]("Circumferrance of Rectangle is ="+2*(length + breadth));
}
public static void main(String args[])
{
Rectangle r = new Rectangle(10,20);
Rectangle r1 = new Rectangle(10,20);
[Link]("String Representation = "+ [Link]());
[Link]("Class Name = "+[Link]());
[Link]("Hash Code = "+[Link]());
[Link]("[Link](r1) = "+ [Link](r1));
}
}
—----------------------------------------------------------------------------------------------------------------------------
import [Link];
class Bank {
static String bankName;
static {
bankName = "Secure Bank India";
[Link]("Bank Initialized: " + bankName);
}
String customerName;
int accountNo;
Bank(String name, int accNo) {
customerName = name;
accountNo = accNo;
}
public static int generateOTP() {
Random rand = new Random();
int otp = 100000 + [Link](900000); // 6-digit OTP
return otp;
}
public void requestOTP() {
[Link]("\nCustomer: " + customerName);
[Link]("Account Number: " + accountNo);
int otp = generateOTP();
[Link]("Generated OTP: " + otp);
}
public static void main(String[] args) {
Bank c1 = new Bank("Ravi Kumar", 12345678);
[Link]();
Bank c2 = new Bank("Priya Sharma", 87654321);
[Link]();
}
}
—----------------------------------------------------------------------------------------------------------------------------
Inheritance
Single Inheritance
class Parent {
// parent class
}
class Child extends Parent {
// child class
}
Example :
class Account
{
int accountNo;
double balance;
void setData(int accNo, double bal) {
accountNo = accNo;
balance = bal;
}
void displayBalance() {
[Link]("Account Number: " + accountNo);
[Link]("Balance: ₹" + balance);
}
}
class SavingAccount extends Account {
double interestRate = 0.05;
void calculateInterest() {
double interest = balance * interestRate;
[Link]("Interest (5%): ₹" + interest);
}
}
class Test
{
public static void main(String[] args)
{
SavingAccount sa = new SavingAccount();
[Link](123456, 10000);
[Link]();
[Link]();
}
}
—-------------------------------------------------------------------
MultiLevel
// Base class
class Person {
String name;
void getName(String n) {
name = n;
}
void showName() {
[Link]("Name: " + name);
}
}
// Derived class from Person
class Employee extends Person {
int empId;
void getEmpId(int id) {
empId = id;
}
void showEmpId() {
[Link]("Employee ID: " + empId);
}
}
// Derived class from Employee
class Manager extends Employee {
String department;
void getDepartment(String dept) {
department = dept;
}
void showDetails() {
showName(); // from Person
showEmpId(); // from Employee
[Link]("Department: " + department);
}
public static void main(String[] args) {
Manager m = new Manager();
[Link]("Anita Sharma");
[Link](2025);
[Link]("Finance");
[Link]();
}
}
—------------------------------------------------------------------------------
Hierarchical inheritance
// Parent class
class Account {
int accountNo;
double balance;
void setAccount(int accNo, double bal) {
accountNo = accNo;
balance = bal;
}
void showAccount() {
[Link]("Account Number: " + accountNo);
[Link]("Balance: ₹" + balance);
}
}
// Child class 1
class SavingsAccount extends Account {
void calculateInterest() {
double interest = balance * 0.05;
[Link]("Savings Interest (5%): ₹" + interest);
}
}
// Child class 2
class CurrentAccount extends Account {
void checkMinimumBalance() {
if (balance < 1000) {
[Link]("Warning: Balance below minimum requirement!");
} else {
[Link]("Balance is sufficient.");
}
}
}
// Main class to test both
public class Bank {
public static void main(String[] args) {
// Object of SavingsAccount
SavingsAccount sa = new SavingsAccount();
[Link](1111, 5000);
[Link]("Savings Account Info:");
[Link]();
[Link]();
[Link]();
// Object of CurrentAccount
CurrentAccount ca = new CurrentAccount();
[Link](2222, 800);
[Link]("Current Account Info:");
[Link]();
[Link]();
}
}
—------------------------------------------------------------------------------------
Use of ‘Super’ keyword
✅ Use of super Keyword in Java
The super keyword in Java is used to refer to the immediate parent class object.
It helps in accessing:
1. Parent class constructor
2. Parent class methods
3. Parent class data members (variables)
📌 Key Points:
● super is used only in child class.
● The call to super() must be the first statement in the constructor.
● You can use super to override and extend the behavior of parent class.
Example :
🔹 1. Using super to access parent class variable
If the child class has a variable with the same name as the parent class,
[Link] is used to refer to the parent class variable.
class Animal {
String color = "White";
}
class Dog extends Animal {
String color = "Black";
void printColor() {
[Link]("Dog color: " + color); // Child class color
[Link]("Animal color: " + [Link]); // Parent class
color
public class TestSuper1 {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
🔹 2. Using super to call parent class method
class Animal {
void sound() {
[Link]("Animal makes a sound");
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
void displaySound() {
sound(); // Calls child class method
[Link](); // Calls parent class method
public class TestSuper2 {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
🔹 3. Using super() to call parent class constructor
class Animal {
Animal() {
[Link]("Animal constructor called");
class Dog extends Animal {
Dog() {
super(); // Call parent class constructor
[Link]("Dog constructor called");
public class TestSuper3 {
public static void main(String[] args) {
Dog d = new Dog();
Method Overriding and Runtime Polymorphism
✅ Method Overriding in Java
Method Overriding occurs when a subclass provides a specific implementation of
a method that is already defined in its superclass. It allows runtime polymorphism.
🔹 Key Points:
● Method name, return type, and parameters must be the same.
● It occurs between parent and child classes.
● The overridden method in the child class replaces the parent class version at
runtime.
class Bank {
double getInterestRate() {
return 5.0; // base interest rate
}
}
class SBI extends Bank {
double getInterestRate() {
return 6.5;
}
}
class HDFC extends Bank {
double getInterestRate() {
return 7.0;
}
}
public class BankExample {
public static void main(String[] args) {
Bank b1 = new SBI(); // Upcasting
Bank b2 = new HDFC(); // Upcasting
[Link]("SBI Interest Rate: " + [Link]() + "%");
[Link]("HDFC Interest Rate: " + [Link]() + "%");
}
}
—---------------------------------------------------------------------------------------------------------
Runtime Polymorphism
✅ What is Runtime Polymorphism in Java?
Runtime Polymorphism (also called Dynamic Method Dispatch) in Java is a form
of method overriding where the call to an overridden method is resolved at
runtime and not at compile time.
It is one of the core concepts of Object-Oriented Programming and provides
flexibility and reusability by allowing the same method name to behave differently
based on the object type.
Example :
// Parent class
class Bank {
double getRateOfInterest() {
return 0.0;
}
}
// Child class 1
class SBI extends Bank {
double getRateOfInterest() {
return 5.5;
}
}
// Child class 2
class HDFC extends Bank {
double getRateOfInterest() {
return 6.75;
}
}
// Child class 3
class ICICI extends Bank {
double getRateOfInterest() {
return 6.25;
}
}
// Main class
public class TestPolymorphism {
public static void main(String[] args) {
Bank b; // superclass reference
b = new SBI(); // upcasting
[Link]("SBI Interest Rate: " + [Link]() + "%");
b = new HDFC(); // upcasting
[Link]("HDFC Interest Rate: " + [Link]() + "%");
b = new ICICI(); // upcasting
[Link]("ICICI Interest Rate: " + [Link]() + "%");
}
}
🔁 What is Upcasting in Java?
These are type conversion techniques used with inheritance and
polymorphism in Java, allowing objects to be treated as instances of their
superclass or subclass.
Usage of ‘final’ keyword
Final Variable in Java :
In Java, the final keyword is used to declare constants. When a variable is
marked as final, its value cannot be changed once initialized.
🔑 Key Points about final Variable:
● A final variable must be initialized only once.
● Once assigned, the value cannot be modified.
Example :
public class FinalExample {
public static void main(String[] args) {
final int number = 10; // final variable
// number = 20;
[Link]("The value is: " + number);
Example 2 :
public class FinalExample {
public static void main(String[] args)
int x = 10 ;
final int y = 20;
[Link]("x is "+x);
[Link]("x is "+y);
x = 30;
y = 40;
[Link]("x is "+x);
[Link]("x is "+y);
🔐 final Methods in Java – Explanation with Example
In Java, when a method is declared as final, it cannot be overridden by
subclasses.
It is used To prevent modification of important logic in subclasses.
Example :
class Bank {
final void displayInterestRate()
[Link]("Interest Rate is 5%");
class SBI extends Bank {
// ❌ This will cause an error if uncommented
/*
void displayInterestRate() {
[Link]("SBI Interest Rate is 6%");
*/
public class Main {
public static void main(String[] args) {
SBI sbi = new SBI();
[Link](); // Calls the final method from Bank class
🧱 final Class in Java – Explanation with Suitable Example
In Java, when a class is declared as final, it cannot be inherited (i.e., no
other class can extend it).
✅ Why Use a final Class?
● To prevent inheritance for security or design reasons.
● To protect code logic from being altered in subclasses.
Example
final class Bank
void showBankDetails() {
[Link]("Bank: RBI");
// ❌ This will cause a compile-time error
/*
class SBI extends Bank {
void showBankDetails() {
[Link]("Bank: SBI");
*/
public class Main {
public static void main(String[] args) {
Bank b = new Bank();
[Link]();
---------------------------------------------------------------------------------------------------------
Abstract Classes and Abstract methods in java
Example :
import [Link];
abstract class Shape {
abstract void area(); // abstract method
void display()
[Link]("\n Non_Abstract method of class Shape");
class Rectangle extends Shape {
double length, breadth;
Rectangle(double l, double b) {
length = l;
breadth = b;
// Implementation of abstract method
void area() {
double a = length * breadth;
[Link]("Area of Rectangle: " + a);
class Circle extends Shape {
double radius;
Circle(double r) {
radius = r;
void area() {
double a = [Link] * radius * radius;
[Link]("Area of Circle: " + a);
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter length of rectangle: ");
double l = [Link]();
[Link]("Enter breadth of rectangle: ");
double b = [Link]();
Shape rect = new Rectangle(l, b); // Upcasting
[Link]();
[Link]();
[Link]();
[Link]("Enter radius of circle: ");
double r = [Link]();
Shape circ = new Circle(r); // Upcasting
[Link]();
[Link]();
Example 2 :
// Abstract class
abstract class Student {
int id;
String name;
String phone;
String email;
// Constructor
Student(int id, String name, String phone, String email) {
[Link] = id;
[Link] = name;
[Link] = phone;
[Link] = email;
// 3 abstract methods
abstract void displayDetails();
abstract String getCourse();
abstract void calculateFees();
// Subclass 1 – Undergraduate Student
class UGStudent extends Student {
UGStudent(int id, String name, String phone, String email) {
super(id, name, phone, email);
void displayDetails() {
[Link]("UG Student Details:");
[Link]("ID: " + id + ", Name: " + name);
[Link]("Phone: " + phone + ", Email: " + email);
String getCourse() {
return "[Link] Computer Science";
void calculateFees() {
[Link]("UG Course Fee: ₹55,000 per year");
// Subclass 2 – Postgraduate Student
class PGStudent extends Student {
PGStudent(int id, String name, String phone, String email) {
super(id, name, phone, email);
void displayDetails() {
[Link]("PG Student Details:");
[Link]("ID: " + id + ", Name: " + name);
[Link]("Phone: " + phone + ", Email: " + email);
String getCourse() {
return "[Link] Data Science";
void calculateFees() {
[Link]("PG Course Fee: ₹60,000 per year");
// Main class
public class Main {
public static void main(String[] args) {
// UG Student
Student ug = new UGStudent(101, "Aarti Sharma", "9876543210",
"aarti@[Link]");
[Link]();
[Link]("Course: " + [Link]());
[Link]();
[Link]();
// PG Student
Student pg = new PGStudent(202, "Ravi Kumar", "9123456789",
"ravi@[Link]");
[Link]();
[Link]("Course: " + [Link]());
[Link]();
—------------------------------------------------------------------------------------------------------------------
Interface
✅ Syntax:
interface InterfaceName {
void method1();
void method2();
Example
// [Link]
interface BankAccount {
void deposit(double amount);
void withdraw(double amount);
void displayBalance();
class SavingsAccount implements BankAccount {
private double balance = 0;
public void deposit(double amount) {
balance += amount;
[Link]("Savings: Deposited Rs" + amount);
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
[Link]("Savings: Withdrawn Rs" + amount);
} else {
[Link]("Savings: Insufficient balance");
public void displayBalance() {
[Link]("Savings Balance: Rs" + balance);
class CurrentAccount implements BankAccount {
private double balance = 0;
public void deposit(double amount) {
balance += amount;
[Link]("Current: Deposited Rs" + amount);
public void withdraw(double amount) {
if (balance - amount >= -5000) { // overdraft limit
balance -= amount;
[Link]("Current: Withdrawn Rs" + amount);
} else {
[Link]("Current: Overdraft limit exceeded");
public void displayBalance() {
[Link]("Current Balance: Rs" + balance);
public class Main {
public static void main(String[] args) {
// Using interface reference
BankAccount sa = new SavingsAccount();
[Link](1000);
[Link](300);
[Link]();
[Link]();
BankAccount ca = new CurrentAccount();
[Link](2000);
[Link](6500); // should allow within overdraft
[Link]();
Example 2 :
// [Link]
interface Employee {
void displayDetails();
double calculateSalary();
class FullTimeEmployee implements Employee {
private int id;
private String name;
private double basicSalary;
private double hra;
public FullTimeEmployee(int id, String name, double basicSalary, double hra) {
[Link] = id;
[Link] = name;
[Link] = basicSalary;
[Link] = hra;
public void displayDetails() {
[Link]("Full-Time Employee Details:");
[Link]("ID: " + id + ", Name: " + name);
public double calculateSalary() {
double salary = basicSalary + hra;
[Link]("Total Salary: ₹" + salary);
return salary;
class PartTimeEmployee implements Employee {
private int id;
private String name;
private int hoursWorked;
private double hourlyRate;
public PartTimeEmployee(int id, String name, int hoursWorked, double
hourlyRate) {
[Link] = id;
[Link] = name;
[Link] = hoursWorked;
[Link] = hourlyRate;
public void displayDetails() {
[Link]("Part-Time Employee Details:");
[Link]("ID: " + id + ", Name: " + name);
public double calculateSalary() {
double salary = hoursWorked * hourlyRate;
[Link]("Total Salary: ₹" + salary);
return salary;
public class Main {
public static void main(String[] args) {
// Full-time employee
Employee e1 = new FullTimeEmployee(101, "Anita Verma", 25000, 5000);
[Link]();
[Link]();
[Link]();
// Part-time employee
Employee e2 = new PartTimeEmployee(202, "Rohan Mehta", 40, 300);
[Link]();
[Link]();
—--------------------------------------------------------------------------------------------------------
Runtime Polymorphism using Interface
Extending interface ;
🔷 What is Extending an Interface in Java?
In Java, interfaces can extend other interfaces using the extends keyword.
This allows one interface to inherit the abstract method declarations from another
interface, just like classes can inherit from other classes.
🔹 Key Points:
● An interface cannot implement another interface, it can only extend it.
● An interface can extend multiple interfaces (this is Java’s way of
achieving multiple inheritance for interfaces).
● The child interface inherits all the abstract methods from the parent
interface(s).
🔶 Syntax:
interface ParentInterface {
void method1();
}
interface ChildInterface extends ParentInterface {
void method2();
}
Example 1 :
/// Base interface
interface Person {
void displayPersonDetails();
}
// Extended interface
interface Employee extends Person {
void displayEmployeeDetails();
}
// Class implementing the extended interface
class Manager implements Employee {
String name;
int age;
String employeeId;
String department;
// Constructor to initialize employee data
Manager(String name, int age, String employeeId, String department) {
[Link] = name;
[Link] = age;
[Link] = employeeId;
[Link] = department;
}
public void displayPersonDetails() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
public void displayEmployeeDetails() {
[Link]("Employee ID: " + employeeId);
[Link]("Department: " + department);
}
}
// Main class
public class Main {
public static void main(String[] args) {
// Creating Manager object using constructor
Manager mgr = new Manager("Rajesh Kumar", 35, "EMP1023", "HR");
// Displaying details
[Link](); // From Person interface
[Link](); // From Employee interface
}
}
Extending Multiple Interfaces:
✅ What is Multiple Inheritance?
Multiple inheritance means a class can inherit features (fields and methods) from
more than one parent class.
class A {
void show() {
[Link]("A");
class B {
void show() {
[Link]("B");
// ❌ Invalid in Java
class C extends A, B {
// Which show() should be called? A or B?
Example 2
interface A {
void show();
interface B {
void display();
class C implements A, B {
public void show() {
[Link]("From A");
public void display() {
[Link]("From B");
public class Main {
public static void main(String[] args) {
C obj = new C();
[Link]();
[Link]();
Example 3
// Salary interface
interface Salary {
void calculateSalary();
// Tax interface
interface Tax {
void calculateTax();
// Employee class implementing both interfaces (Multiple Inheritance)
class Employee implements Salary, Tax {
String name;
int empId;
double basicSalary;
double grossSalary;
double taxAmount;
double netSalary;
Employee(int id, String name, double basicSalary) {
[Link] = id;
[Link] = name;
[Link] = basicSalary;
// From Salary interface
public void calculateSalary() {
double hra = 0.2 * basicSalary;
double da = 0.1 * basicSalary;
grossSalary = basicSalary + hra + da;
[Link]("Gross Salary: ₹" + grossSalary);
// From Tax interface
public void calculateTax() {
taxAmount = 0.1 * grossSalary; // 10% tax
netSalary = grossSalary - taxAmount;
[Link]("Tax Deducted: ₹" + taxAmount);
[Link]("Net Salary: ₹" + netSalary);
public void displayDetails() {
[Link]("Employee ID: " + empId);
[Link]("Name: " + name);
[Link]("Basic Salary: ₹" + basicSalary);
// Main class
public class Main {
public static void main(String[] args) {
Employee e1 = new Employee(101, "Rahul Mehta", 30000);
[Link]();
[Link]();
[Link]();
—------------------------------------------------------------------------------------------------------------------
Nested Interface
✅ What is a Nested Interface in Java?
A nested interface is an interface declared within another class or interface.
Syntax :
class Outer
{
interface Inner
{
void show();
}
}
Example
// Outer interface
interface Vehicle {
void start();
// Nested interface inside interface
interface Engine {
void engineType();
}
}
// Class implementing the inner interface
class Car implements [Link] {
public void engineType() {
[Link]("Car has a Petrol Engine");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Car c = new Car();
[Link]();
}
}
—------------------------------------------------------------------------------------------