1
Complete Java Classes and Objects Notes 🚀
A comprehensive guide covering Object-Oriented Programming concepts, classes, objects, construct‐
ors, static members, and the this keyword with detailed explanations, code examples, memory
diagrams, and best practices
📚 TABLE OF CONTENTS
1. Introduction to OOP and Classes
2. Class Definition
3. Object Creation
4. Instance Variables and Methods
5. Static Members
6. Best Practices and Common Mistakes
1. Introduction to OOP and Classes
🤔 What is Object-Oriented Programming (OOP)?
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design
around objects rather than functions and logic. An object is an entity that contains data (attributes/
properties) and code (methods/behaviors) that operates on that data. OOP focuses on the objects that
developers want to manipulate rather than the logic required to manipulate them.
Simple Definition: OOP is a way of organizing code by grouping related data and functions together
into objects, which are instances of classes.
Analogy: Think of OOP like a car manufacturing blueprint 🚗:
- Class = Blueprint/design for a car (defines what a car should have)
- Object = Actual car built from the blueprint (real, usable car)
- Attributes = Color, model, engine type (characteristics)
- Methods = Start, stop, accelerate (behaviors/actions)
From one blueprint (class), you can create many cars (objects), each with its own color, model, and
state.
2
🎯 Why Object-Oriented Programming?
Before OOP (Procedural Programming):
// Data and functions are separate
String studentName = "John";
int studentAge = 20;
double studentGPA = 3.8;
// Functions operate on data
void displayStudent(String name, int age, double gpa) {
[Link](name + ", " + age + ", " + gpa);
}
// Problems:
// - Data and related functions are scattered
// - No encapsulation or data protection
// - Difficult to manage for large programs
// - Hard to reuse code
With OOP:
// Data and functions are bundled together
class Student {
// Data (attributes)
private String name;
private int age;
private double gpa;
// Functions (methods)
public void displayInfo() {
[Link](name + ", " + age + ", " + gpa);
}
}
// Benefits:
// ✅ Data and related functions are together
// ✅ Encapsulation protects data
// ✅ Easy to manage and scale
// ✅ Reusable and maintainable
📊 Four Pillars of OOP
OOP is built on four fundamental principles:
FOUR PILLARS OF OOP
|
____________________|____________________
| | | |
ENCAPSULATION ABSTRACTION INHERITANCE POLYMORPHISM
| | | |
Data hiding Hide Inherit Many forms
& bundling complexity properties Same name,
different behavior
3
1️⃣ Encapsulation 🔒
Definition: Bundling data (variables) and methods (functions) that operate on the data into a single
unit (class), and restricting direct access to some of the object’s components.
Key Points:
- Data hiding using access modifiers (private, protected, public)
- Controlled access through getter and setter methods
- Protects object integrity by preventing external interference
Example:
class BankAccount {
// Private data - cannot be accessed directly
private double balance;
// Public methods - controlled access
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public double getBalance() {
return balance; // Read-only access
}
}
// Usage
BankAccount account = new BankAccount();
// [Link] = -1000; // ❌ Error: balance is private
[Link](1000); // ✅ Controlled access through method
Real-World Analogy: ATM Machine 🏧
- You can’t directly access the cash inside
- You interact through a defined interface (buttons, screen)
- The machine controls and validates your actions
2️⃣ Abstraction 🎭
Definition: Hiding complex implementation details and showing only the essential features of an
object. Focusing on what an object does rather than how it does it.
Key Points:
- Show only relevant information
- Hide unnecessary details
- Simplify complex reality by modeling classes appropriate to the problem
Example:
4
class Car {
// Complex internal implementation hidden
private void fuelInjection() { /* complex code */ }
private void igniteEngine() { /* complex code */ }
private void transmissionControl() { /* complex code */ }
// Simple public interface
public void start() {
fuelInjection();
igniteEngine();
[Link]("Car started");
}
}
// User doesn't need to know the internal complexity
Car myCar = new Car();
[Link](); // Simple to use!
Real-World Analogy: Driving a car 🚗
- You use steering wheel, pedals, gear shift
- You don’t need to know about engine combustion, transmission mechanics
- Simple interface hides complex machinery
3️⃣ Inheritance 👪
Definition: A mechanism where a new class (child/subclass) inherits properties and behaviors from an
existing class (parent/superclass). Promotes code reusability.
Key Points:
- “IS-A” relationship (Dog IS-A Animal)
- Child class inherits fields and methods from parent
- Child can add its own unique features
- Promotes code reuse
Example:
5
// Parent class
class Animal {
protected String name;
public void eat() {
[Link](name + " is eating");
}
}
// Child class inherits from Animal
class Dog extends Animal {
public void bark() {
[Link](name + " is barking");
}
}
// Usage
Dog myDog = new Dog();
[Link] = "Buddy";
[Link](); // Inherited method
[Link](); // Own method
Real-World Analogy: Family inheritance 👨👩👦
- Children inherit traits from parents (eye color, height genes)
- Children also develop their own unique characteristics
4️⃣ Polymorphism 🎭
Definition: The ability of an object to take many forms. Same method name behaves differently
based on the object calling it.
Key Points:
- “Many forms” - one interface, multiple implementations
- Method overloading (compile-time polymorphism)
- Method overriding (runtime polymorphism)
Example:
6
class Animal {
public void makeSound() {
[Link]("Some generic animal sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
[Link]("Woof! Woof!");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
[Link]("Meow! Meow!");
}
}
// Polymorphism in action
Animal animal1 = new Dog();
Animal animal2 = new Cat();
[Link](); // Woof! Woof!
[Link](); // Meow! Meow!
Real-World Analogy: Remote control 📺
- Same “Power” button works differently for TV, AC, stereo
- Same interface, different behavior based on device
🤔 What is a Class?
A class is a blueprint or template for creating objects. It defines:
- What data the objects will have (attributes/fields/instance variables)
- What actions the objects can perform (methods/functions)
Simple Definition: A class is like a cookie cutter 🍪 - it defines the shape and structure, but it’s not
the actual cookie. Objects are the cookies made from that cutter.
Key Point: A class itself doesn’t consume memory (until you create objects from it). It’s just a defini‐
tion.
🤔 What is an Object?
An object is an instance of a class. It’s a real entity that:
- Occupies memory
- Has a state (values of its attributes)
- Can perform actions (through methods)
Simple Definition: An object is the actual thing created from a class blueprint. If class is a blueprint
for a house, the object is the actual house built from it.
7
🏗️ Class vs Object
Aspect Class Object
Definition Blueprint/Template Instance created from class
Memory No memory allocation Memory allocated when cre‐
ated
Creation Defined once using class Created using new keyword
keyword
Example class Car { } Car myCar = new Car();
Analogy Architectural blueprint Actual building
Nature Logical entity Physical entity
Existence One class definition Many objects from one class
💡 Real-World Examples of Classes and Objects
Example 1: Student
Class: Student (Blueprint)
- Attributes: name, rollNumber, age, grade
- Methods: study(), attendClass(), takeExam()
Objects: Individual students
- Object 1: Alice, Roll 101, Age 20, Grade A
- Object 2: Bob, Roll 102, Age 21, Grade B
- Object 3: Charlie, Roll 103, Age 20, Grade A
Example 2: Mobile Phone
Class: MobilePhone (Blueprint)
- Attributes: brand, model, color, batteryLevel
- Methods: makeCall(), sendMessage(), playMusic()
Objects: Individual phones
- Object 1: iPhone 15, Blue, 85% battery
- Object 2: Samsung Galaxy S24, Black, 60% battery
- Object 3: Google Pixel 8, White, 90% battery
Example 3: Bank Account
Class: BankAccount (Blueprint)
- Attributes: accountNumber, holderName, balance, accountType
- Methods: deposit(), withdraw(), checkBalance()
Objects: Individual accounts
- Object 1: Acc# 12345, John Doe, $5000, Savings
8
- Object 2: Acc# 67890, Jane Smith, $12000, Checking
- Object 3: Acc# 11111, Bob Wilson, $3500, Savings
9
📝 Simple Example: Understanding Class and Object
// Class Definition - Blueprint
class Dog {
// Attributes (What a dog has)
String name;
String breed;
int age;
String color;
// Methods (What a dog can do)
void bark() {
[Link](name + " says: Woof! Woof!");
}
void eat() {
[Link](name + " is eating");
}
void sleep() {
[Link](name + " is sleeping");
}
}
// Main class to test
public class DogTest {
public static void main(String[] args) {
// Creating objects from Dog class
// Object 1
Dog dog1 = new Dog();
[Link] = "Max";
[Link] = "Labrador";
[Link] = 3;
[Link] = "Golden";
// Object 2
Dog dog2 = new Dog();
[Link] = "Bella";
[Link] = "German Shepherd";
[Link] = 5;
[Link] = "Brown";
// Using objects
[Link]("=== Dog 1 ===");
[Link]("Name: " + [Link]);
[Link]("Breed: " + [Link]);
[Link]("Age: " + [Link]);
[Link]();
[Link]();
[Link]("\n=== Dog 2 ===");
[Link]("Name: " + [Link]);
[Link]("Breed: " + [Link]);
[Link]("Age: " + [Link]);
[Link]();
[Link]();
}
}
Output:
10
=== Dog 1 ===
Name: Max
Breed: Labrador
Age: 3
Max says: Woof! Woof!
Max is eating
=== Dog 2 ===
Name: Bella
Breed: German Shepherd
Age: 5
Bella says: Woof! Woof!
Bella is sleeping
Explanation:
- One class (Dog) defined with attributes and methods
- Two objects (dog1, dog2) created from the same class
- Each object has its own data (different names, breeds, ages)
- Both objects can perform the same actions (bark, eat, sleep)
🔑 Key Takeaways
✅ OOP organizes code around objects that contain data and behavior
✅ Four pillars: Encapsulation, Abstraction, Inheritance, Polymorphism
✅ Class is a blueprint/template (doesn’t consume memory)
✅ Object is an instance of a class (consumes memory, has real data)
✅ One class can create multiple objects, each with unique data
✅ OOP promotes code reusability, modularity, and maintainability
✅ Real-world entities are modeled as classes and objects
✅ Java is a pure object-oriented language (everything except primitives is an object)
2. Class Definition
🤔 What is a Class Definition?
A class definition is the complete specification of a class, including its structure, members, and
behaviors. It defines:
- The name of the class
- Data members (variables/fields)
- Methods (functions)
- Constructors (special methods to initialize objects)
- Access modifiers (who can access what)
Simple Definition: Class definition is like writing a recipe 📋 - it lists all ingredients (variables) and
steps (methods) needed to create something.
11
📊 Class Structure Diagram
12
✍️ Syntax of Class Definition
[access_modifier] class ClassName {
// 1. Instance Variables (Fields/Attributes)
[access_modifier] dataType variableName;
// 2. Static Variables (Class Variables)
[access_modifier] static dataType variableName;
// 3. Static Block
static {
// Initialization code
}
// 4. Instance Block
{
// Initialization code
}
// 5. Constructors
[access_modifier] ClassName(parameters) {
// Initialization code
}
// 6. Instance Methods
[access_modifier] returnType methodName(parameters) {
// Method body
}
// 7. Static Methods
[access_modifier] static returnType methodName(parameters) {
// Method body
}
}
📋 Components of a Class
A class can contain the following components (also called members):
13
CLASS COMPONENTS
|
____________________|____________________
| | |
VARIABLES CONSTRUCTORS METHODS
| | |
• Instance Default • Instance
• Static Parameterized • Static
• Local Copy • Abstract (in abstract class)
Constructor
Chaining
|
________________
| |
BLOCKS NESTED CLASSES
| |
• Static • Inner Class
• Instance • Static Nested
• Local Class
• Anonymous Class
🔍 1. Class Name and Declaration
Rules for Class Names:
Rule Description Example
Must start with letter Can’t start with digit ✅ Student ❌ 1Student
Can contain letters, digits, No special characters except ✅ Student_123 ❌ Stu‐
underscore _ and $ dent-123
Case-sensitive Student ≠ student Student and student are
different
Cannot be a keyword Reserved words not allowed ❌ class , int , public
Follow naming convention Start with uppercase, use ✅ StudentDetails ❌ stu‐
PascalCase dentdetails
Meaningful name Descriptive and clear ✅ BankAccount ❌ BA
14
Examples:
// ✅ Good class names
class Student { }
class BankAccount { }
class MobilePhone { }
class EmployeeDetails { }
class StudentManagementSystem { }
// ❌ Bad class names
class student { } // Should start with uppercase
class 123Student { } // Can't start with digit
class Student-Info { } // Can't use hyphen
class s { } // Not meaningful
class class { } // Reserved keyword
🔍 2. Instance Variables (Fields/Attributes)
Instance variables are variables declared inside a class but outside any method. Each object
gets its own copy of instance variables.
Syntax:
[access_modifier] dataType variableName [= initialValue];
Example:
class Student {
// Instance variables
private String name;
private int rollNumber;
private double gpa;
private boolean isActive;
// Each Student object will have its own name, rollNumber, gpa, isActive
}
Characteristics:
• Belong to object (not class)
• Different for each object
• Default values assigned automatically if not initialized
• Stored in heap memory (along with object)
• Can have access modifiers
🔍 3. Static Variables (Class Variables)
Static variables are variables declared with static keyword. They are shared by all objects of
the class - only one copy exists.
15
Syntax:
[access_modifier] static dataType variableName [= initialValue];
Example:
class Student {
// Instance variables (unique for each object)
private String name;
private int rollNumber;
// Static variable (shared by all objects)
private static String universityName = "ABC University";
private static int totalStudents = 0;
}
Characteristics:
• Belong to class (not objects)
• Same for all objects (shared)
• Only one copy in memory
• Accessed using class name: [Link]
• Stored in method area (not heap)
🔍 4. Methods
Methods define the behavior or actions that objects can perform. They contain executable code.
Syntax:
[access_modifier] [static] returnType methodName(parameters) {
// Method body
// Code to execute
[return value;] // If returnType is not void
}
Types of Methods:
a) Instance Methods
class Calculator {
// Instance method
public int add(int a, int b) {
return a + b;
}
}
// Usage
Calculator calc = new Calculator();
int result = [Link](5, 3); // Called on object
16
b) Static Methods
class Calculator {
// Static method
public static int multiply(int a, int b) {
return a * b;
}
}
// Usage
int result = [Link](5, 3); // Called on class
🔍 5. Constructors
Constructors are special methods used to initialize objects when they are created. They have
the same name as the class and no return type.
Syntax:
[access_modifier] ClassName(parameters) {
// Initialization code
}
Example:
class Student {
private String name;
private int age;
// Constructor
public Student(String name, int age) {
[Link] = name;
[Link] = age;
}
}
// Usage
Student student = new Student("Alice", 20);
More details on constructors in later sections.
🔍 6. Blocks
Blocks are sections of code enclosed in curly braces {} . Java has two types:
17
a) Static Block
class MyClass {
static {
[Link]("Static block executed");
// Executes once when class is loaded
}
}
b) Instance Block
class MyClass {
{
[Link]("Instance block executed");
// Executes every time an object is created
}
}
18
📝 Complete Class Example
19
public class Student {
// 1. Static variable (shared by all)
private static String universityName = "XYZ University";
private static int totalStudents = 0;
// 2. Instance variables (unique for each object)
private String name;
private int rollNumber;
private double gpa;
// 3. Static block (runs once when class loads)
static {
[Link]("Student class loaded");
[Link]("University: " + universityName);
}
// 4. Instance block (runs before each constructor)
{
totalStudents++;
[Link]("New student object created");
}
// 5. Constructor (initializes object)
public Student(String name, int rollNumber, double gpa) {
[Link] = name;
[Link] = rollNumber;
[Link] = gpa;
}
// 6. Instance method
public void displayInfo() {
[Link]("Name: " + name);
[Link]("Roll: " + rollNumber);
[Link]("GPA: " + gpa);
}
// 7. Static method
public static void showTotalStudents() {
[Link]("Total students: " + totalStudents);
}
// 8. Getter methods
public String getName() {
return name;
}
public int getRollNumber() {
return rollNumber;
}
// 9. Setter methods
public void setGPA(double gpa) {
if (gpa >= 0 && gpa <= 4.0) {
[Link] = gpa;
}
}
}
// Test class
public class StudentTest {
public static void main(String[] args) {
[Link]("Creating students...\n");
20
Student student1 = new Student("Alice", 101, 3.8);
[Link]();
[Link]();
Student student2 = new Student("Bob", 102, 3.5);
[Link]();
[Link]();
[Link]();
}
}
Output:
Student class loaded
University: XYZ University
Creating students...
New student object created
Name: Alice
Roll: 101
GPA: 3.8
New student object created
Name: Bob
Roll: 102
GPA: 3.5
Total students: 2
🎨 Access Modifiers in Classes
Access modifiers control the visibility and accessibility of class members.
Modifier Same Class Same Package Subclass Other Package
(Different
Package)
private ✅ Yes ❌ No ❌ No ❌ No
default (no ✅ Yes ✅ Yes ❌ No ❌ No
modifier)
protected ✅ Yes ✅ Yes ✅ Yes ❌ No
public ✅ Yes ✅ Yes ✅ Yes ✅ Yes
21
Examples:
public class AccessModifiersDemo {
// Private - accessible only within this class
private int privateVar = 10;
// Default - accessible within same package
int defaultVar = 20;
// Protected - accessible within package and subclasses
protected int protectedVar = 30;
// Public - accessible everywhere
public int publicVar = 40;
// Private method
private void privateMethod() {
[Link]("Private method");
}
// Public method
public void publicMethod() {
[Link]("Public method");
privateMethod(); // Can call private method within same class
}
}
📏 Class Naming Conventions
Following Java naming conventions makes code more readable and professional:
Element Convention Example
Class Name PascalCase (first letter upper‐ Student , BankAccount , Em‐
case) ployeeDetails
Variable Name camelCase (first letter lower‐ studentName , totalMarks ,
case) isActive
Method Name camelCase with verb getName() , calculat‐
eTotal() , isEligible()
Constant ALL_CAPS with underscore MAX_SIZE , DEFAULT_VALUE ,
PI
Package Name all lowercase [Link]
22
Example:
package [Link];
public class StudentManagementSystem {
// Constants
private static final int MAX_STUDENTS = 100;
private static final double MIN_GPA = 0.0;
// Instance variables
private String studentName;
private int rollNumber;
private boolean isActive;
// Method
public void calculateTotalMarks() {
// Method body
}
}
23
📝 Example: Complete Class with All Components
24
public class BankAccount {
// Static variable - shared by all accounts
private static int totalAccounts = 0;
private static final double MINIMUM_BALANCE = 500.0;
// Instance variables - unique for each account
private String accountNumber;
private String holderName;
private double balance;
private String accountType;
// Static block - executes when class loads
static {
[Link]("=== Bank Account System Initialized ===");
[Link]("Minimum balance: $" + MINIMUM_BALANCE);
}
// Instance block - executes before constructor
{
totalAccounts++;
[Link]("Creating new account... Total accounts: " + totalAc‐
counts);
}
// Constructor - initializes object
public BankAccount(String accountNumber, String holderName, double
initialBalance) {
[Link] = accountNumber;
[Link] = holderName;
[Link] = initialBalance;
[Link] = "Savings";
}
// Instance methods
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Deposited: $" + amount);
[Link]("New balance: $" + balance);
} else {
[Link]("Invalid amount");
}
}
public void withdraw(double amount) {
if (amount > 0 && (balance - amount) >= MINIMUM_BALANCE) {
balance -= amount;
[Link]("Withdrawn: $" + amount);
[Link]("New balance: $" + balance);
} else {
[Link]("Insufficient balance or below minimum");
}
}
public void displayAccountInfo() {
[Link]("\n=== Account Information ===");
[Link]("Account Number: " + accountNumber);
[Link]("Holder Name: " + holderName);
[Link]("Balance: $" + balance);
[Link]("Account Type: " + accountType);
}
25
// Static method
public static void displayTotalAccounts() {
[Link]("Total accounts created: " + totalAccounts);
}
// Getters
public double getBalance() {
return balance;
}
public String getHolderName() {
return holderName;
}
}
// Test class
public class BankTest {
public static void main(String[] args) {
// Create first account
BankAccount account1 = new BankAccount("ACC001", "Alice Johnson", 5000.0);
[Link]();
[Link](1500);
[Link](2000);
[Link]("\n" + "=".repeat(40) + "\n");
// Create second account
BankAccount account2 = new BankAccount("ACC002", "Bob Smith", 3000.0);
[Link]();
[Link]();
[Link]();
}
}
Output:
26
=== Bank Account System Initialized ===
Minimum balance: $500.0
Creating new account... Total accounts: 1
=== Account Information ===
Account Number: ACC001
Holder Name: Alice Johnson
Balance: $5000.0
Account Type: Savings
Deposited: $1500.0
New balance: $6500.0
Withdrawn: $2000.0
New balance: $4500.0
========================================
Creating new account... Total accounts: 2
=== Account Information ===
Account Number: ACC002
Holder Name: Bob Smith
Balance: $3000.0
Account Type: Savings
Total accounts created: 2
🔑 Key Takeaways
✅ Class definition specifies structure, data, and behavior of objects
✅ Components: Variables, Constructors, Methods, Blocks
✅ Instance variables: Unique for each object
✅ Static variables: Shared by all objects (one copy)
✅ Access modifiers: Control visibility (private, default, protected, public)
✅ Naming conventions: PascalCase for classes, camelCase for variables/methods
✅ Blocks: Static block (class load), Instance block (object creation)
✅ A well-designed class encapsulates data and provides controlled access
3. Object Creation
🤔 What is Object Creation?
Object creation is the process of creating an instance of a class in memory. When you create an ob‐
ject:
- Memory is allocated in the heap
- Instance variables are initialized
- Constructor is invoked
- A reference to the object is returned
Simple Definition: Object creation is like building a house from a blueprint 🏠 - the blueprint
(class) doesn’t take space, but the actual house (object) does.
27
📊 Object Creation Process Diagram
✍️ Syntax for Creating Objects
ClassName referenceVariable = new ClassName(arguments);
Components:
1. ClassName - Type of the object
2. referenceVariable - Name to reference the object
3. new - Keyword that allocates memory
4. ClassName(arguments) - Constructor call
28
🔍 Step-by-Step Object Creation Process
Step 1: Declaration
↓
ClassName referenceVariable;
(Reference variable created in STACK)
Step 2: Instantiation (using 'new')
↓
new ClassName();
(Memory allocated in HEAP)
Step 3: Initialization (Constructor call)
↓
ClassName(arguments)
(Constructor executes, initializes object)
Step 4: Assignment
↓
referenceVariable = [object reference];
(Reference stored in variable)
29
📝 Example: Creating Objects
class Student {
String name;
int rollNumber;
// Constructor
public Student(String name, int rollNumber) {
[Link] = name;
[Link] = rollNumber;
}
public void displayInfo() {
[Link]("Name: " + name + ", Roll: " + rollNumber);
}
}
public class ObjectCreationDemo {
public static void main(String[] args) {
// Method 1: Declaration and Instantiation together
Student student1 = new Student("Alice", 101);
// Method 2: Declaration first, instantiation later
Student student2; // Declaration
student2 = new Student("Bob", 102); // Instantiation
// Method 3: Multiple references to same object
Student student3 = new Student("Charlie", 103);
Student student3Copy = student3; // Both refer to same object
// Using objects
[Link]();
[Link]();
[Link]();
[Link](); // Same as student3
}
}
Output:
Name: Alice, Roll: 101
Name: Bob, Roll: 102
Name: Charlie, Roll: 103
Name: Charlie, Roll: 103
🔍 The ‘new’ Keyword
The new keyword is responsible for:
1. Allocating memory for the object in heap
2. Returning the reference (memory address) of allocated memory
3. Invoking the constructor to initialize the object
30
Example:
Student student = new Student("Alice", 101);
// ^^^
// |
// new keyword:
// - Allocates memory in heap
// - Calls constructor
// - Returns reference
📊 Memory Allocation: Heap vs Stack
🧠 Understanding Stack and Heap Memory
STACK MEMORY HEAP MEMORY
(Local variables, (Objects, instance variables)
references)
┌──────────────┐ ┌────────────────────────────┐
│ │ │ │
│ student1 ───┼──────────────>│ Student Object │
│ (reference) │ │ ┌──────────────┐ │
│ │ │ │ name: "Alice"│ │
└──────────────┘ │ │ roll: 101 │ │
│ └──────────────┘ │
│ │
└────────────────────────────┘
Key Points:
• Reference variable (student1) → Stack
• Actual object → Heap
• Reference "points to" or "refers to" the object
31
📝 Detailed Memory Example
public class MemoryDemo {
public static void main(String[] args) {
// Creating first object
Student s1 = new Student("Alice", 101);
// Creating second object
Student s2 = new Student("Bob", 102);
// Creating reference to existing object
Student s3 = s1; // s3 and s1 point to same object
}
}
/* Memory Representation:
STACK HEAP
┌─────────┐ ┌─────────────────────┐
│ s1 ───┼───────────────────>│ Object 1 │
└─────────┘ │ name: "Alice" │
│ roll: 101 │
┌─────────┐ └─────────────────────┘
│ s2 ───┼───────────────┐
└─────────┘ │ ┌─────────────────────┐
└───>│ Object 2 │
┌─────────┐ │ name: "Bob" │
│ s3 ───┼────────────────────>│ roll: 102 │
└─────────┘ | └─────────────────────┘
|
(points to same
object as s1)
*/
🔄 Multiple Object Creation
You can create multiple objects from the same class, each with its own data:
32
class Car {
String brand;
String model;
int year;
String color;
public Car(String brand, String model, int year, String color) {
[Link] = brand;
[Link] = model;
[Link] = year;
[Link] = color;
}
public void displayInfo() {
[Link](year + " " + brand + " " + model + " (" + color + ")");
}
}
public class MultipleObjects {
public static void main(String[] args) {
// Creating multiple Car objects
Car car1 = new Car("Toyota", "Camry", 2023, "Silver");
Car car2 = new Car("Honda", "Civic", 2022, "Blue");
Car car3 = new Car("Tesla", "Model 3", 2024, "White");
Car car4 = new Car("BMW", "X5", 2023, "Black");
// Using objects
[Link]("=== Car Collection ===");
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:
=== Car Collection ===
2023 Toyota Camry (Silver)
2022 Honda Civic (Blue)
2024 Tesla Model 3 (White)
2023 BMW X5 (Black)
🎭 Anonymous Objects
An anonymous object is an object created without storing its reference in a variable. It’s useful
for one-time use.
Syntax:
new ClassName(arguments).method();
33
Example:
class Calculator {
public int add(int a, int b) {
return a + b;
}
public int multiply(int a, int b) {
return a * b;
}
}
public class AnonymousObjectDemo {
public static void main(String[] args) {
// Regular object (with reference)
Calculator calc = new Calculator();
int result1 = [Link](5, 3);
[Link]("Using reference: " + result1);
// Anonymous object (no reference)
int result2 = new Calculator().add(10, 20);
[Link]("Anonymous object: " + result2);
// Another anonymous object
int result3 = new Calculator().multiply(4, 5);
[Link]("Anonymous object: " + result3);
// Anonymous object with method chaining
new Calculator().add(5, 10); // Result not stored
}
}
Output:
Using reference: 8
Anonymous object: 30
Anonymous object: 20
When to use:
- When you need an object only once
- For method chaining
- To avoid cluttering code with unnecessary variable names
🔗 Object Reference Variables
An object reference variable holds the memory address (reference) of an object, not the actual
object data.
34
Key Concepts:
1. Multiple References to Same Object
Student s1 = new Student("Alice", 101);
Student s2 = s1; // s2 refers to same object as s1
[Link] = "Alice Updated";
[Link]([Link]); // Output: Alice Updated
// Both s1 and s2 point to the same object
2. Null Reference
Student s1 = null; // s1 doesn't point to any object
// [Link](); // NullPointerException!
if (s1 != null) {
[Link](); // Safe check
}
3. Reassigning References
Student s1 = new Student("Alice", 101);
Student s2 = new Student("Bob", 102);
s1 = s2; // Now s1 refers to Bob's object
// Alice's object becomes eligible for garbage collection
35
📝 Complete Example: Object References
class Person {
String name;
int age;
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
public void displayInfo() {
[Link]("Name: " + name + ", Age: " + age);
}
}
public class ReferenceDemo {
public static void main(String[] args) {
// Creating first object
Person person1 = new Person("Alice", 25);
[Link]("person1:");
[Link]();
// Creating second reference to same object
Person person2 = person1;
[Link]("\nperson2 (refers to same object as person1):");
[Link]();
// Modifying through person2
[Link] = "Alice Smith";
[Link] = 26;
// Check person1 (will show updated values)
[Link]("\nperson1 after modification through person2:");
[Link]();
// Creating new object and assigning to person2
person2 = new Person("Bob", 30);
[Link]("\nperson2 after new assignment:");
[Link]();
// person1 unchanged
[Link]("\nperson1 (unchanged):");
[Link]();
// Null reference
Person person3 = null;
if (person3 != null) {
[Link]();
} else {
[Link]("\nperson3 is null");
}
}
}
Output:
36
person1:
Name: Alice, Age: 25
person2 (refers to same object as person1):
Name: Alice, Age: 25
person1 after modification through person2:
Name: Alice Smith, Age: 26
person2 after new assignment:
Name: Bob, Age: 30
person1 (unchanged):
Name: Alice Smith, Age: 26
person3 is null
🗑️ Garbage Collection and Object Lifecycle
What Happens to Objects?
When an object has no references pointing to it, it becomes eligible for garbage collection.
Student s1 = new Student("Alice", 101); // Object created
s1 = new Student("Bob", 102); // Alice's object has no reference
// Alice's object → Garbage Collection
// Or explicitly set to null
s1 = null; // Bob's object eligible for GC
Object Lifecycle:
Created → In Use → No References → Garbage Collected → Memory Freed
↓ ↓ ↓ ↓ ↓
new Accessible Orphaned finalize() Reclaimed
keyword via ref (no refs) (optional)
37
📝 Example: Garbage Collection
class Demo {
String name;
public Demo(String name) {
[Link] = name;
[Link](name + " object created");
}
// finalize() called before garbage collection (deprecated but for demo)
@Override
protected void finalize() {
[Link](name + " object is being garbage collected");
}
}
public class GarbageCollectionDemo {
public static void main(String[] args) {
Demo obj1 = new Demo("Object1");
Demo obj2 = new Demo("Object2");
Demo obj3 = new Demo("Object3");
[Link]("\nRemoving references...");
// Remove reference - obj1 eligible for GC
obj1 = null;
// Reassign reference - obj2 eligible for GC
obj2 = obj3;
// Request garbage collection (not guaranteed to run immediately)
[Link]();
[Link]("\nProgram continuing...");
try {
[Link](1000); // Give time for GC
} catch (InterruptedException e) {
[Link]();
}
}
}
Possible Output (order may vary):
Object1 object created
Object2 object created
Object3 object created
Removing references...
Program continuing...
Object2 object is being garbage collected
Object1 object is being garbage collected
38
🔑 Key Takeaways
✅ Object creation uses new keyword: ClassName obj = new ClassName();
✅ Three steps: Declaration → Instantiation → Initialization
✅ Stack stores reference variables, Heap stores actual objects
✅ new keyword allocates memory and calls constructor
✅ Multiple references can point to the same object
✅ Anonymous objects are created without reference variable
✅ null reference means variable doesn’t point to any object
✅ Garbage collection automatically reclaims memory of unused objects
✅ Object becomes eligible for GC when no references point to it
4. Instance Variables and Methods
🤔 What are Instance Variables?
Instance variables (also called member variables, fields, or attributes) are variables declared
inside a class but outside any method. Each object gets its own copy of instance variables, mak‐
ing them unique to each object.
Simple Definition: Instance variables are like personal belongings 👜 of an object - each object
has its own set, separate from other objects.
Analogy: Think of instance variables like student ID cards 🎓:
- Each student (object) has their own card (instance variable)
- Each card has unique information (name, ID, photo)
- One student’s card doesn’t affect another student’s card
✍️ Syntax of Instance Variables
[access_modifier] dataType variableName [= initialValue];
Examples:
class Student {
// Instance variables
private String name; // No initial value
private int rollNumber; // No initial value
private double gpa = 0.0; // With initial value
private boolean isActive = true; // With initial value
}
39
📊 Characteristics of Instance Variables
Characteristic Description
Scope Throughout the class
Lifetime Exists as long as the object exists
Storage Stored in heap memory (with object)
Access Through object reference: [Link]
Default Values Automatically initialized if not explicitly set
Unique Each object has its own copy
Declaration Inside class, outside methods
🔍 Default Values of Instance Variables
If you don’t initialize instance variables, Java assigns default values:
Data Type Default Value
byte, short, int, long 0
float, double 0.0
boolean false
char '\u0000' (null character)
Reference types (String, Objects) null
40
Example:
class DefaultValues {
// Instance variables without initialization
int number; // Default: 0
double price; // Default: 0.0
boolean flag; // Default: false
String name; // Default: null
char letter; // Default: '\u0000'
public void displayDefaults() {
[Link]("number: " + number);
[Link]("price: " + price);
[Link]("flag: " + flag);
[Link]("name: " + name);
[Link]("letter code: " + (int)letter);
}
}
public class DefaultValuesDemo {
public static void main(String[] args) {
DefaultValues obj = new DefaultValues();
[Link]();
}
}
Output:
number: 0
price: 0.0
flag: false
name: null
letter code: 0
📝 Declaring and Initializing Instance Variables
Method 1: Initialize at Declaration
class Product {
private String name = "Unknown";
private double price = 0.0;
private int quantity = 0;
}
41
Method 2: Initialize in Constructor
class Product {
private String name;
private double price;
private int quantity;
public Product(String name, double price, int quantity) {
[Link] = name;
[Link] = price;
[Link] = quantity;
}
}
Method 3: Initialize Using Setter Methods
class Product {
private String name;
private double price;
public void setName(String name) {
[Link] = name;
}
public void setPrice(double price) {
[Link] = price;
}
}
// Usage
Product product = new Product();
[Link]("Laptop");
[Link](999.99);
🔍 Accessing Instance Variables
Instance variables can be accessed:
1. Within the class - directly by name or using [Link]
2. Outside the class - using object reference: [Link] (if not private)
42
Example:
class Person {
// Private instance variables
private String name;
private int age;
public Person(String name, int age) {
// Access within class using 'this'
[Link] = name;
[Link] = age;
}
public void displayInfo() {
// Access within class directly
[Link]("Name: " + name);
[Link]("Age: " + age);
}
// Getter methods for outside access
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class AccessDemo {
public static void main(String[] args) {
Person person = new Person("Alice", 25);
// Can't access private variables directly
// [Link]([Link]); // ❌ Compilation error
// Access through getter methods
[Link]("Name: " + [Link]()); // ✅ Works
[Link]("Age: " + [Link]()); // ✅ Works
// Or through public method
[Link]();
}
}
Output:
Name: Alice
Age: 25
Name: Alice
Age: 25
43
🎯 The ‘this’ Keyword
The this keyword is a reference to the current object - the object whose method or constructor is
being called.
Uses of ‘this’ Keyword:
1. Distinguish Between Instance Variables and Parameters
class Student {
private String name;
private int age;
public Student(String name, int age) {
// '[Link]' = instance variable
// 'name' = parameter
[Link] = name; // Without 'this', would refer to parameter
[Link] = age;
}
}
2. Call Instance Methods
class Calculator {
private int result;
public void add(int a, int b) {
result = a + b;
[Link](); // Calling another method using 'this'
}
public void display() {
[Link]("Result: " + result);
}
}
44
3. Return Current Object
class Builder {
private String name;
private int age;
public Builder setName(String name) {
[Link] = name;
return this; // Return current object for method chaining
}
public Builder setAge(int age) {
[Link] = age;
return this; // Return current object
}
}
// Method chaining
Builder builder = new Builder().setName("Alice").setAge(25);
4. Pass Current Object as Argument
class MyClass {
public void method1() {
method2(this); // Pass current object
}
public void method2(MyClass obj) {
// Use the object
}
}
45
📝 Complete Example: Instance Variables
46
class Employee {
// Instance variables
private int employeeId;
private String name;
private String department;
private double salary;
private boolean isActive;
// Constructor
public Employee(int employeeId, String name, String department, double salary) {
[Link] = employeeId;
[Link] = name;
[Link] = department;
[Link] = salary;
[Link] = true; // Default value
}
// Display method
public void displayInfo() {
[Link]("=== Employee Information ===");
[Link]("ID: " + employeeId);
[Link]("Name: " + name);
[Link]("Department: " + department);
[Link]("Salary: $" + salary);
[Link]("Status: " + (isActive ? "Active" : "Inactive"));
}
// Getters
public int getEmployeeId() {
return employeeId;
}
public String getName() {
return name;
}
// Setters
public void setSalary(double salary) {
if (salary > 0) {
[Link] = salary;
}
}
public void setDepartment(String department) {
[Link] = department;
}
public void deactivate() {
[Link] = false;
}
}
public class InstanceVariablesDemo {
public static void main(String[] args) {
// Create employee objects
Employee emp1 = new Employee(101, "Alice Johnson", "Engineering", 75000);
Employee emp2 = new Employee(102, "Bob Smith", "Marketing", 65000);
// Display information
[Link]();
[Link]();
[Link]();
47
// Modify through setters
[Link]("\n--- After Updates ---");
[Link](80000);
[Link]("Senior Engineering");
[Link]();
}
}
Output:
=== Employee Information ===
ID: 101
Name: Alice Johnson
Department: Engineering
Salary: $75000.0
Status: Active
=== Employee Information ===
ID: 102
Name: Bob Smith
Department: Marketing
Salary: $65000.0
Status: Active
--- After Updates ---
=== Employee Information ===
ID: 101
Name: Alice Johnson
Department: Senior Engineering
Salary: $80000.0
Status: Active
4.2 Instance Methods
🤔 What are Instance Methods?
Instance methods are functions defined inside a class that operate on instance variables and
define the behavior of objects. They are called on objects and can access instance variables directly.
Simple Definition: Instance methods are like actions or behaviors 🎬 that objects can perform.
Analogy: Think of instance methods like student actions 🎓:
- study() - student can study
- attendClass() - student can attend class
- takeExam() - student can take exam
48
✍️ Syntax of Instance Methods
[access_modifier] returnType methodName([parameters]) {
// Method body
// Code to execute
[return value;] // If returnType is not void
}
Components:
1. Access Modifier: public , private , protected , or default
2. Return Type: Data type of value returned ( void if nothing returned)
3. Method Name: Identifier following naming conventions
4. Parameters: Input values (optional)
5. Method Body: Code to execute
6. Return Statement: Return value (if return type is not void)
📝 Types of Instance Methods
1. Methods Without Parameters and Without Return Value
class Printer {
public void printMessage() {
[Link]("Hello, World!");
}
}
// Usage
Printer p = new Printer();
[Link](); // Output: Hello, World!
2. Methods With Parameters but Without Return Value
class Printer {
public void printMessage(String message) {
[Link]("Message: " + message);
}
}
// Usage
Printer p = new Printer();
[Link]("Welcome"); // Output: Message: Welcome
49
3. Methods Without Parameters but With Return Value
class Calculator {
private int value = 10;
public int getValue() {
return value;
}
}
// Usage
Calculator calc = new Calculator();
int result = [Link]();
[Link](result); // Output: 10
4. Methods With Parameters and With Return Value
class Calculator {
public int add(int a, int b) {
return a + b;
}
}
// Usage
Calculator calc = new Calculator();
int sum = [Link](5, 3);
[Link](sum); // Output: 8
50
📝 Complete Example: Instance Methods
51
class Rectangle {
// Instance variables
private double length;
private double width;
// Constructor
public Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}
// Method 1: Calculate area (with return)
public double calculateArea() {
return length * width;
}
// Method 2: Calculate perimeter (with return)
public double calculatePerimeter() {
return 2 * (length + width);
}
// Method 3: Display information (no return)
public void displayInfo() {
[Link]("=== Rectangle Info ===");
[Link]("Length: " + length);
[Link]("Width: " + width);
[Link]("Area: " + calculateArea());
[Link]("Perimeter: " + calculatePerimeter());
}
// Method 4: Check if square (with return)
public boolean isSquare() {
return length == width;
}
// Method 5: Resize (with parameters, no return)
public void resize(double newLength, double newWidth) {
if (newLength > 0 && newWidth > 0) {
[Link] = newLength;
[Link] = newWidth;
[Link]("Rectangle resized");
} else {
[Link]("Invalid dimensions");
}
}
// Method 6: Compare with another rectangle
public boolean isLargerThan(Rectangle other) {
return [Link]() > [Link]();
}
}
public class InstanceMethodsDemo {
public static void main(String[] args) {
// Create rectangles
Rectangle rect1 = new Rectangle(5, 3);
Rectangle rect2 = new Rectangle(4, 4);
// Using instance methods
[Link]("Rectangle 1:");
[Link]();
[Link]("Is Square? " + [Link]());
52
[Link]("\nRectangle 2:");
[Link]();
[Link]("Is Square? " + [Link]());
// Comparing rectangles
[Link]("\nIs rect1 larger than rect2? " +
[Link](rect2));
// Resizing
[Link]("\nResizing rect1...");
[Link](6, 4);
[Link]();
}
}
Output:
Rectangle 1:
=== Rectangle Info ===
Length: 5.0
Width: 3.0
Area: 15.0
Perimeter: 16.0
Is Square? false
Rectangle 2:
=== Rectangle Info ===
Length: 4.0
Width: 4.0
Area: 16.0
Perimeter: 16.0
Is Square? true
Is rect1 larger than rect2? false
Resizing rect1...
Rectangle resized
=== Rectangle Info ===
Length: 6.0
Width: 4.0
Area: 24.0
Perimeter: 20.0
🔄 Method Overloading
Method overloading is a feature that allows a class to have multiple methods with the same
name but different parameters (different number or type of parameters).
Rules for Method Overloading:
1. Same method name
2. Different parameter list (number, type, or order)
3. Return type can be different (but not sufficient alone)
4. Access modifiers can be different
53
Example:
class Calculator {
// Overloaded add methods
// Method 1: Two integers
public int add(int a, int b) {
[Link]("Adding two integers");
return a + b;
}
// Method 2: Three integers
public int add(int a, int b, int c) {
[Link]("Adding three integers");
return a + b + c;
}
// Method 3: Two doubles
public double add(double a, double b) {
[Link]("Adding two doubles");
return a + b;
}
// Method 4: Integer and double
public double add(int a, double b) {
[Link]("Adding int and double");
return a + b;
}
}
public class OverloadingDemo {
public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]("Result: " + [Link](5, 3));
[Link]();
[Link]("Result: " + [Link](5, 3, 2));
[Link]();
[Link]("Result: " + [Link](5.5, 3.2));
[Link]();
[Link]("Result: " + [Link](5, 3.5));
}
}
Output:
Adding two integers
Result: 8
Adding three integers
Result: 10
Adding two doubles
Result: 8.7
Adding int and double
Result: 8.5
54
🎯 Method Parameters and Arguments
Parameters are variables in the method definition.
Arguments are actual values passed when calling the method.
class Demo {
// 'a' and 'b' are PARAMETERS
public int add(int a, int b) {
return a + b;
}
}
// 5 and 3 are ARGUMENTS
Demo obj = new Demo();
int result = [Link](5, 3);
📊 Pass by Value in Java
Java is strictly pass-by-value. For:
- Primitives: Copy of the value is passed
- Objects: Copy of the reference is passed (but still pass-by-value)
Example: Primitives
class PassByValueDemo {
public void modify(int x) {
x = x * 2;
[Link]("Inside method: " + x);
}
public static void main(String[] args) {
PassByValueDemo obj = new PassByValueDemo();
int num = 10;
[Link]("Before: " + num);
[Link](num);
[Link]("After: " + num); // Original unchanged
}
}
Output:
Before: 10
Inside method: 20
After: 10
55
Example: Objects
class Student {
int age;
}
class PassByValueDemo2 {
public void modifyAge(Student s) {
[Link] = 30; // Modifies object (reference copied)
}
public void reassign(Student s) {
s = new Student(); // Local reassignment (doesn't affect original)
[Link] = 50;
}
public static void main(String[] args) {
PassByValueDemo2 obj = new PassByValueDemo2();
Student student = new Student();
[Link] = 20;
[Link]("Original age: " + [Link]);
[Link](student);
[Link]("After modifyAge: " + [Link]); // Changed
[Link](student);
[Link]("After reassign: " + [Link]); // Unchanged
}
}
Output:
Original age: 20
After modifyAge: 30
After reassign: 30
4.3 Constructors
🤔 What is a Constructor?
A constructor is a special method that is automatically called when an object is created. Its primary
purpose is to initialize the object’s instance variables.
Simple Definition: A constructor is like a setup assistant 🛠️ that prepares a new object when it’s
created.
Analogy: Think of a constructor like setting up a new phone 📱:
- When you buy a phone (create object), setup runs automatically (constructor)
- Setup configures language, Wi-Fi, accounts (initializes variables)
- You get a ready-to-use phone (initialized object)
56
📊 Constructor Flow Diagram
✍️ Constructor Syntax
[access_modifier] ClassName([parameters]) {
// Initialization code
}
Key Points:
- Same name as class
- No return type (not even void )
- Automatically called when object is created using new
57
📋 Characteristics of Constructors
Characteristic Description
Name Must be same as class name
Return Type No return type (not even void)
Invocation Called automatically when object created
Purpose Initialize instance variables
Overloading Can have multiple constructors with different
parameters
Inheritance Not inherited by subclasses
Types Default, Parameterized, Copy
🔍 Types of Constructors
1️⃣ Default Constructor (No-Argument Constructor)
A constructor with no parameters. If you don’t define any constructor, Java provides a default con‐
structor automatically.
Java-Provided Default Constructor:
class Student {
String name;
int age;
// No constructor defined
// Java provides: public Student() { }
}
// Usage
Student s = new Student(); // Calls default constructor
58
User-Defined Default Constructor:
class Student {
String name;
int age;
// User-defined default constructor
public Student() {
name = "Unknown";
age = 0;
[Link]("Default constructor called");
}
}
public class DefaultConstructorDemo {
public static void main(String[] args) {
Student s1 = new Student();
[Link]("Name: " + [Link]);
[Link]("Age: " + [Link]);
}
}
Output:
Default constructor called
Name: Unknown
Age: 0
2️⃣ Parameterized Constructor
A constructor that accepts parameters to initialize instance variables with specific values.
59
class Student {
String name;
int age;
double gpa;
// Parameterized constructor
public Student(String name, int age, double gpa) {
[Link] = name;
[Link] = age;
[Link] = gpa;
[Link]("Parameterized constructor called");
}
public void displayInfo() {
[Link]("Name: " + name + ", Age: " + age + ", GPA: " + gpa);
}
}
public class ParameterizedConstructorDemo {
public static void main(String[] args) {
Student s1 = new Student("Alice", 20, 3.8);
[Link]();
Student s2 = new Student("Bob", 22, 3.5);
[Link]();
}
}
Output:
Parameterized constructor called
Name: Alice, Age: 20, GPA: 3.8
Parameterized constructor called
Name: Bob, Age: 22, GPA: 3.5
3️⃣ Copy Constructor
A constructor that creates a new object as a copy of an existing object.
60
class Student {
String name;
int age;
// Parameterized constructor
public Student(String name, int age) {
[Link] = name;
[Link] = age;
}
// Copy constructor
public Student(Student other) {
[Link] = [Link];
[Link] = [Link];
[Link]("Copy constructor called");
}
public void displayInfo() {
[Link]("Name: " + name + ", Age: " + age);
}
}
public class CopyConstructorDemo {
public static void main(String[] args) {
Student s1 = new Student("Alice", 20);
[Link]("Original object:");
[Link]();
// Create copy using copy constructor
Student s2 = new Student(s1);
[Link]("\nCopied object:");
[Link]();
// Modify original
[Link] = "Alice Updated";
[Link]("\nAfter modifying original:");
[Link]("Original:");
[Link]();
[Link]("Copy:");
[Link](); // Copy unchanged
}
}
Output:
Original object:
Name: Alice, Age: 20
Copy constructor called
Copied object:
Name: Alice, Age: 20
After modifying original:
Original:
Name: Alice Updated, Age: 20
Copy:
Name: Alice, Age: 20
61
🔄 Constructor Overloading
A class can have multiple constructors with different parameters.
class Rectangle {
double length;
double width;
// Constructor 1: No parameters (default)
public Rectangle() {
[Link] = 1.0;
[Link] = 1.0;
[Link]("Default constructor");
}
// Constructor 2: One parameter (square)
public Rectangle(double side) {
[Link] = side;
[Link] = side;
[Link]("Square constructor");
}
// Constructor 3: Two parameters (rectangle)
public Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
[Link]("Rectangle constructor");
}
public void displayInfo() {
[Link]("Length: " + length + ", Width: " + width);
[Link]("Area: " + (length * width));
}
}
public class ConstructorOverloadingDemo {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
[Link]();
[Link]();
Rectangle r2 = new Rectangle(5);
[Link]();
[Link]();
Rectangle r3 = new Rectangle(5, 3);
[Link]();
}
}
Output:
62
Default constructor
Length: 1.0, Width: 1.0
Area: 1.0
Square constructor
Length: 5.0, Width: 5.0
Area: 25.0
Rectangle constructor
Length: 5.0, Width: 3.0
Area: 15.0
🔗 Constructor Chaining
Constructor chaining is calling one constructor from another constructor using this() or super() .
Using this() - Call Another Constructor in Same Class
class Student {
String name;
int age;
String course;
// Constructor 1: One parameter
public Student(String name) {
this(name, 18); // Call constructor 2
[Link]("Constructor 1");
}
// Constructor 2: Two parameters
public Student(String name, int age) {
this(name, age, "Not Assigned"); // Call constructor 3
[Link]("Constructor 2");
}
// Constructor 3: Three parameters
public Student(String name, int age, String course) {
[Link] = name;
[Link] = age;
[Link] = course;
[Link]("Constructor 3");
}
public void displayInfo() {
[Link]("Name: " + name + ", Age: " + age + ", Course: " + course);
}
}
public class ConstructorChainingDemo {
public static void main(String[] args) {
Student s = new Student("Alice");
[Link]();
}
}
Output:
63
Constructor 3
Constructor 2
Constructor 1
Name: Alice, Age: 18, Course: Not Assigned
Note: this() must be the first statement in the constructor.
64
📝 Complete Constructor Example
65
class BankAccount {
private String accountNumber;
private String holderName;
private double balance;
private String accountType;
// Constructor 1: Default
public BankAccount() {
this("ACC000", "Unknown", 0.0, "Savings");
[Link]("Default constructor");
}
// Constructor 2: Account number and name
public BankAccount(String accountNumber, String holderName) {
this(accountNumber, holderName, 0.0, "Savings");
[Link]("Constructor with 2 parameters");
}
// Constructor 3: Account number, name, and initial balance
public BankAccount(String accountNumber, String holderName, double balance) {
this(accountNumber, holderName, balance, "Savings");
[Link]("Constructor with 3 parameters");
}
// Constructor 4: All parameters
public BankAccount(String accountNumber, String holderName, double balance,
String accountType) {
[Link] = accountNumber;
[Link] = holderName;
[Link] = balance;
[Link] = accountType;
[Link]("Constructor with all parameters");
}
public void displayInfo() {
[Link]("=== Account Info ===");
[Link]("Account: " + accountNumber);
[Link]("Holder: " + holderName);
[Link]("Balance: $" + balance);
[Link]("Type: " + accountType);
}
}
public class ConstructorCompleteDemo {
public static void main(String[] args) {
[Link]("Creating Account 1:");
BankAccount acc1 = new BankAccount();
[Link]();
[Link]("\nCreating Account 2:");
BankAccount acc2 = new BankAccount("ACC001", "Alice");
[Link]();
[Link]("\nCreating Account 3:");
BankAccount acc3 = new BankAccount("ACC002", "Bob", 5000);
[Link]();
[Link]("\nCreating Account 4:");
BankAccount acc4 = new BankAccount("ACC003", "Charlie", 10000, "Checking");
[Link]();
}
}
66
Output:
Creating Account 1:
Constructor with all parameters
Default constructor
=== Account Info ===
Account: ACC000
Holder: Unknown
Balance: $0.0
Type: Savings
Creating Account 2:
Constructor with all parameters
Constructor with 2 parameters
=== Account Info ===
Account: ACC001
Holder: Alice
Balance: $0.0
Type: Savings
Creating Account 3:
Constructor with all parameters
Constructor with 3 parameters
=== Account Info ===
Account: ACC002
Holder: Bob
Balance: $5000.0
Type: Savings
Creating Account 4:
Constructor with all parameters
=== Account Info ===
Account: ACC003
Holder: Charlie
Balance: $10000.0
Type: Checking
⚠️ Important Points About Constructors
1. If You Define Any Constructor, Default Constructor is NOT Provided
class Demo {
int x;
// Parameterized constructor defined
public Demo(int x) {
this.x = x;
}
}
// Demo d = new Demo(); // ❌ Error: No default constructor
Demo d = new Demo(10); // ✅ Correct
67
2. Constructor Cannot Be Static
class Demo {
// public static Demo() { } // ❌ Error: Constructors cannot be static
}
3. Constructor Cannot Be Final
class Demo {
// public final Demo() { } // ❌ Error: Constructors cannot be final
}
4. Constructors Are Not Inherited
Child class doesn’t inherit parent’s constructor (but can call using super() ).
🔑 Key Takeaways - Instance Variables, Methods, and Constructors
✅ Instance variables are unique to each object (stored in heap)
✅ Default values assigned automatically if not initialized
✅ ‘this’ keyword refers to current object
✅ Instance methods define object behavior
✅ Method overloading: Same name, different parameters
✅ Java is pass-by-value (copy of value or reference)
✅ Constructors initialize objects (same name as class, no return type)
✅ Three types: Default, Parameterized, Copy
✅ Constructor overloading: Multiple constructors with different parameters
✅ Constructor chaining: Call another constructor using this()
✅ If you define any constructor, Java doesn’t provide default constructor
5. Static Members
🤔 What are Static Members?
Static members (static variables and methods) belong to the class rather than to individual objects.
They are shared by all objects of the class. Only one copy of static members exists in memory, re‐
gardless of how many objects are created.
Simple Definition: Static members are like shared resources 🏛️ that belong to the entire class, not
individual objects.
Analogy: Think of static members like a school library 📚:
- Instance variables = Student’s personal books (each student has their own)
- Static variables = School library (shared by all students)
- All students access the same library, not separate copies
68
📊 Static vs Instance Comparison
📋 Static vs Instance - Quick Comparison
Aspect Static Members Instance Members
Belongs to Class Object
Copies One copy (shared) One copy per object
Memory Method Area Heap
Access [Link] [Link]
Declaration static keyword No static keyword
Initialization When class loads When object created
Lifecycle Entire program Object’s lifetime
Can access Only static members Both static and instance
5.1 Static Variables (Class Variables)
🤔 What are Static Variables?
Static variables (also called class variables) are variables declared with the static keyword. They
are shared by all objects of the class - there’s only one copy in memory.
69
Simple Definition: Static variables are like class-wide shared data that all objects can access and
modify.
✍️ Syntax
[access_modifier] static dataType variableName [= initialValue];
Examples:
class Student {
// Static variable (shared by all students)
static String universityName = "ABC University";
static int totalStudents = 0;
// Instance variables (unique for each student)
String name;
int rollNumber;
}
70
📝 Complete Example: Static Variables
class Student {
// Static variables (shared)
static String universityName = "ABC University";
static int totalStudents = 0;
// Instance variables (unique)
String name;
int rollNumber;
// Constructor
public Student(String name, int rollNumber) {
[Link] = name;
[Link] = rollNumber;
totalStudents++; // Increment static counter
}
public void displayInfo() {
[Link]("Name: " + name);
[Link]("Roll: " + rollNumber);
[Link]("University: " + universityName); // Access static vari‐
able
[Link]("Total Students: " + totalStudents);
}
}
public class StaticVariableDemo {
public static void main(String[] args) {
[Link]("University: " + [Link]);
[Link]("Total Students: " + [Link]);
[Link]();
// Create first student
Student s1 = new Student("Alice", 101);
[Link]();
[Link]();
// Create second student
Student s2 = new Student("Bob", 102);
[Link]();
[Link]();
// Create third student
Student s3 = new Student("Charlie", 103);
[Link]();
[Link]();
// Change static variable
[Link] = "XYZ University";
[Link]("After changing university name:");
[Link](); // All objects see the change
}
}
Output:
71
University: ABC University
Total Students: 0
Name: Alice
Roll: 101
University: ABC University
Total Students: 1
Name: Bob
Roll: 102
University: ABC University
Total Students: 2
Name: Charlie
Roll: 103
University: ABC University
Total Students: 3
After changing university name:
Name: Alice
Roll: 101
University: XYZ University
Total Students: 3
🧠 Memory Representation: Static vs Instance
METHOD AREA (Static) HEAP MEMORY (Objects)
┌──────────────────────┐ ┌─────────────────────┐
│ [Link] │ │ Object 1 (s1) │
│ │ │ name: "Alice" │
│ Static variables: │ │ roll: 101 │
│ universityName ─────┼────┐ └─────────────────────┘
│ = "ABC Univ" │ │
│ totalStudents = 3 │ │ ┌─────────────────────┐
└──────────────────────┘ │ │ Object 2 (s2) │
↑ │ │ name: "Bob" │
│ │ │ roll: 102 │
│ │ └─────────────────────┘
Shared by all │
objects │ ┌─────────────────────┐
└───>│ Object 3 (s3) │
│ name: "Charlie" │
│ roll: 103 │
└─────────────────────┘
• Static variables: ONE copy in Method Area
• Instance variables: SEPARATE copy for each object in Heap
72
📝 Real-World Example: Bank Account Counter
73
class BankAccount {
// Static variable - tracks total accounts across all objects
private static int totalAccounts = 0;
private static double totalBalance = 0.0;
// Instance variables - unique for each account
private String accountNumber;
private String holderName;
private double balance;
// Constructor
public BankAccount(String accountNumber, String holderName, double
initialBalance) {
[Link] = accountNumber;
[Link] = holderName;
[Link] = initialBalance;
// Update static variables
totalAccounts++;
totalBalance += initialBalance;
}
public void deposit(double amount) {
balance += amount;
totalBalance += amount; // Update static total
}
public void displayInfo() {
[Link]("Account: " + accountNumber + " | Holder: " + holderName +
" | Balance: $" + balance);
}
// Static method to display totals
public static void displayBankStats() {
[Link]("=== Bank Statistics ===");
[Link]("Total Accounts: " + totalAccounts);
[Link]("Total Balance: $" + totalBalance);
}
}
public class BankDemo {
public static void main(String[] args) {
// Create accounts
BankAccount acc1 = new BankAccount("ACC001", "Alice", 5000);
BankAccount acc2 = new BankAccount("ACC002", "Bob", 3000);
BankAccount acc3 = new BankAccount("ACC003", "Charlie", 7000);
// Display individual accounts
[Link]();
[Link]();
[Link]();
[Link]();
// Display bank statistics (static method)
[Link]();
// Make a deposit
[Link]("\nAlice deposits $2000...");
[Link](2000);
// Display updated statistics
[Link]();
74
}
}
Output:
Account: ACC001 | Holder: Alice | Balance: $5000.0
Account: ACC002 | Holder: Bob | Balance: $3000.0
Account: ACC003 | Holder: Charlie | Balance: $7000.0
=== Bank Statistics ===
Total Accounts: 3
Total Balance: $15000.0
Alice deposits $2000...
=== Bank Statistics ===
Total Accounts: 3
Total Balance: $17000.0
5.2 Static Methods
🤔 What are Static Methods?
Static methods are methods declared with the static keyword that belong to the class rather than
objects. They can be called without creating an object.
Simple Definition: Static methods are like class-level utilities 🔧 that don’t need individual objects
to work.
✍️ Syntax
[access_modifier] static returnType methodName([parameters]) {
// Method body
}
75
📋 Characteristics of Static Methods
Characteristic Description
Belongs to Class, not objects
Access [Link]()
Can access Only static variables and methods
Cannot access Instance variables or methods directly
Cannot use this or super keywords
Overriding Cannot be overridden (can be hidden)
76
📝 Example: Static Methods
class MathUtils {
// Static variables
static final double PI = 3.14159;
// Static method 1: Calculate circle area
public static double circleArea(double radius) {
return PI * radius * radius;
}
// Static method 2: Calculate rectangle area
public static double rectangleArea(double length, double width) {
return length * width;
}
// Static method 3: Find maximum
public static int max(int a, int b) {
return (a > b) ? a : b;
}
// Static method 4: Check if even
public static boolean isEven(int number) {
return number % 2 == 0;
}
}
public class StaticMethodDemo {
public static void main(String[] args) {
// Call static methods without creating object
double area1 = [Link](5);
[Link]("Circle area: " + area1);
double area2 = [Link](4, 6);
[Link]("Rectangle area: " + area2);
int maximum = [Link](15, 25);
[Link]("Maximum: " + maximum);
[Link]("Is 10 even? " + [Link](10));
[Link]("Is 7 even? " + [Link](7));
}
}
Output:
Circle area: 78.53975
Rectangle area: 24.0
Maximum: 25
Is 10 even? true
Is 7 even? false
77
⚠️ Restrictions on Static Methods
1. Cannot Access Instance Variables Directly
class Demo {
int instanceVar = 10; // Instance variable
static int staticVar = 20; // Static variable
public static void staticMethod() {
// [Link](instanceVar); // ❌ Error
[Link](staticVar); // ✅ OK
}
}
2. Cannot Use ‘this’ or ‘super’
class Demo {
public static void staticMethod() {
// [Link](); // ❌ Error: Cannot use 'this' in static context
}
}
3. Cannot Call Instance Methods Directly
class Demo {
public void instanceMethod() {
[Link]("Instance method");
}
public static void staticMethod() {
// instanceMethod(); // ❌ Error
// Must create object first
Demo obj = new Demo();
[Link](); // ✅ OK
}
}
78
📝 Complete Example: Accessing Rules
class AccessRulesDemo {
// Instance variables
int instanceVar = 100;
// Static variables
static int staticVar = 200;
// Instance method
public void instanceMethod() {
[Link]("=== Instance Method ===");
[Link]("Can access instance var: " + instanceVar); // ✅
[Link]("Can access static var: " + staticVar); // ✅
staticMethod(); // ✅ Can call static method
}
// Static method
public static void staticMethod() {
[Link]("=== Static Method ===");
// [Link](instanceVar); // ❌ Error
[Link]("Can access static var: " + staticVar); // ✅
// To access instance members, need object
AccessRulesDemo obj = new AccessRulesDemo();
[Link]("Access instance var via object: " + [Link]); //
✅
}
public static void main(String[] args) {
// Call static method directly
[Link]();
[Link]();
// Call instance method via object
AccessRulesDemo obj = new AccessRulesDemo();
[Link]();
}
}
Output:
=== Static Method ===
Can access static var: 200
Access instance var via object: 100
=== Instance Method ===
Can access instance var: 100
Can access static var: 200
=== Static Method ===
Can access static var: 200
Access instance var via object: 100
79
5.3 Static Blocks
🤔 What are Static Blocks?
A static block (also called static initializer block) is a block of code that executes once when the
class is loaded into memory, before any object is created.
Simple Definition: Static blocks are like class setup code that runs automatically when the class is
first loaded.
✍️ Syntax
static {
// Code to execute when class loads
// Initialize static variables
}
📝 Example: Static Block
class StaticBlockDemo {
static int x;
static int y;
static int z;
// Static block - executes once when class loads
static {
[Link]("Static block 1 executed");
x = 10;
y = 20;
}
// Can have multiple static blocks - execute in order
static {
[Link]("Static block 2 executed");
z = x + y;
}
public static void display() {
[Link]("x = " + x + ", y = " + y + ", z = " + z);
}
}
public class StaticBlockTest {
public static void main(String[] args) {
[Link]("Main method started");
// Class loads here (if not already loaded)
[Link]();
[Link]("\nCalling again:");
[Link](); // Static block won't execute again
}
}
80
Output:
Main method started
Static block 1 executed
Static block 2 executed
x = 10, y = 20, z = 30
Calling again:
x = 10, y = 20, z = 30
🔄 Execution Order: Static Block, Instance Block, Constructor
class ExecutionOrderDemo {
static int staticVar;
int instanceVar;
// Static block
static {
staticVar = 100;
[Link]("1. Static block executed");
}
// Instance block
{
instanceVar = 200;
[Link]("3. Instance block executed");
}
// Constructor
public ExecutionOrderDemo() {
[Link]("4. Constructor executed");
}
public static void main(String[] args) {
[Link]("2. Main method started");
ExecutionOrderDemo obj1 = new ExecutionOrderDemo();
[Link]();
ExecutionOrderDemo obj2 = new ExecutionOrderDemo();
}
}
Output:
1. Static block executed
2. Main method started
3. Instance block executed
4. Constructor executed
3. Instance block executed
4. Constructor executed
Execution Order:
1. Static block - Once when class loads
81
2. Instance block - Every time object is created (before constructor)
3. Constructor - Every time object is created (after instance block)
5.4 When to Use Static
✅ Use Static When:
Scenario Reason Example
Utility methods Don’t need object state [Link]() , [Link]()
Constants Same value for all [Link] , Integer.MAX_VALUE
Counter Track across all objects Total students, accounts
Factory methods Create objects [Link]()
Shared resources Common to all objects University name, company
name
❌ Don’t Use Static When:
Scenario Reason
Object-specific data Different for each object
Behavior depends on object state Needs instance variables
Polymorphism needed Static methods can’t be overridden
5.5 Static Import
Static import allows you to use static members without class name prefix.
Syntax:
import static [Link];
import static [Link].*; // All static members
82
Example:
// Without static import
import [Link];
public class WithoutStaticImport {
public static void main(String[] args) {
double result1 = [Link](16);
double result2 = [Link](2, 3);
[Link]([Link]);
}
}
// With static import
import static [Link].*;
public class WithStaticImport {
public static void main(String[] args) {
double result1 = sqrt(16); // No Math. prefix needed
double result2 = pow(2, 3);
[Link](PI);
}
}
🔑 Key Takeaways - Static Members
✅ Static members belong to class, not objects
✅ One copy shared by all objects
✅ Access using class name: [Link]
✅ Static variables: Shared data (counters, constants)
✅ Static methods: Utility functions, no object state needed
✅ Static blocks: Initialize static variables, execute once
✅ Static methods cannot access instance members directly
✅ Static methods cannot use this or super
✅ Execution order: Static block → Instance block → Constructor
✅ Use static for utilities, constants, and shared data
83
6. Best Practices and Common Mistakes
✅ Best Practices
1. Encapsulation - Use Private Variables with Getters/Setters
// ✅ GOOD - Encapsulated
class Student {
private String name; // Private
private int age;
// Getter
public String getName() {
return name;
}
// Setter with validation
public void setAge(int age) {
if (age > 0 && age < 120) {
[Link] = age;
}
}
}
// ❌ BAD - Direct access
class Student {
public String name; // Public - anyone can modify
public int age;
}
2. Meaningful Names
// ✅ GOOD
class Employee {
private String employeeName;
private double monthlySalary;
public void calculateAnnualSalary() {
return monthlySalary * 12;
}
}
// ❌ BAD
class Emp {
private String n;
private double s;
public void calc() {
return s * 12;
}
}
84
3. Constructor Overloading for Flexibility
class Rectangle {
private double length;
private double width;
// Default constructor
public Rectangle() {
this(1.0, 1.0);
}
// Square constructor
public Rectangle(double side) {
this(side, side);
}
// Full constructor
public Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}
}
4. Use ‘this’ for Clarity
// ✅ GOOD - Clear distinction
public Student(String name, int age) {
[Link] = name; // Instance variable
[Link] = age;
}
// ❌ CONFUSING - Different names needed
public Student(String n, int a) {
name = n;
age = a;
}
5. Static for Utilities and Constants
class MathUtils {
// Constant
public static final double PI = 3.14159;
// Utility method
public static double circleArea(double radius) {
return PI * radius * radius;
}
}
85
❌ Common Mistakes
Mistake 1: Forgetting to Initialize Objects
// ❌ ERROR
Student student; // Only declared, not created
[Link](); // NullPointerException
// ✅ CORRECT
Student student = new Student();
[Link]();
Mistake 2: Accessing Static Members Through Objects
class Demo {
static int count = 0;
}
// ❌ NOT RECOMMENDED
Demo obj = new Demo();
[Link]++; // Works but confusing
// ✅ CORRECT
[Link]++; // Clear that it's static
Mistake 3: Modifying Object in Method (Pass by Value Confusion)
class Person {
int age;
}
public void modifyAge(Person p) {
[Link] = 30; // ✅ Modifies original object
}
public void reassign(Person p) {
p = new Person(); // ❌ Local reassignment - doesn't affect original
[Link] = 50;
}
86
Mistake 4: Not Using Constructor Chaining
// ❌ CODE DUPLICATION
class Product {
String name;
double price;
public Product(String name) {
[Link] = name;
[Link] = 0.0;
}
public Product(String name, double price) {
[Link] = name;
[Link] = price;
}
}
// ✅ USE CHAINING
class Product {
String name;
double price;
public Product(String name) {
this(name, 0.0); // Call another constructor
}
public Product(String name, double price) {
[Link] = name;
[Link] = price;
}
}
Mistake 5: Using Static When Instance is Needed
// ❌ WRONG - Can't access instance variables
class BankAccount {
private double balance; // Instance variable
public static void deposit(double amount) { // Static method
// balance += amount; // ❌ Error: Can't access instance variable
}
}
// ✅ CORRECT - Instance method
class BankAccount {
private double balance;
public void deposit(double amount) { // Instance method
balance += amount; // ✅ Can access instance variable
}
}
87
📝 Interview Questions
Q1: What is the difference between class and object?
Answer: A class is a blueprint/template that defines structure and behavior, while an object is an
instance of the class that exists in memory with actual data.
Q2: Can we overload constructors?
Answer: Yes, a class can have multiple constructors with different parameters (constructor overload‐
ing).
Q3: What happens if we don’t define any constructor?
Answer: Java provides a default no-argument constructor automatically. But if you define any
constructor, the default is not provided.
Q4: Can we have a class without any objects?
Answer: Yes. We can use static members without creating objects. Example: Math class.
Q5: Why are instance variables called instance variables?
Answer: Because each object (instance) has its own copy of these variables.
Q6: Can we declare main method as non-static?
Answer: No. Main method must be static so JVM can call it without creating an object.
Q7: What is the use of ‘this’ keyword?
Answer: ‘this’ refers to the current object. Used to:
- Distinguish between instance variables and parameters
- Call other constructors
- Pass current object as argument
Q8: Can we override static methods?
Answer: No. Static methods belong to the class, not objects. They can be hidden but not overridden.
🎯 Final Summary
Classes and Objects form the foundation of Object-Oriented Programming in Java:
✅ Classes define structure and behavior (blueprint)
✅ Objects are instances with actual data
✅ Instance variables are unique to each object
✅ Instance methods define object behavior
✅ Constructors initialize objects
✅ Static members belong to class, shared by all
✅ ‘this’ keyword refers to current object
✅ Encapsulation protects data through access control
88
📚 Additional Practice Exercises
Exercise 1: Create a Book Class
Create a Book class with:
- Instance variables: title, author, price, ISBN
- Constructors: default and parameterized
- Methods: displayInfo(), applyDiscount(double percentage)
- Static variable: totalBooks
- Static method: getTotalBooks()
Exercise 2: Create a Circle Class
Create a Circle class with:
- Instance variable: radius
- Static variable: PI = 3.14159
- Constructor to initialize radius
- Methods: calculateArea(), calculateCircumference()
- Static method: compareCircles(Circle c1, Circle c2)
Exercise 3: Create a Counter Class
Create a Counter class with:
- Instance variable: count (initialized to 0)
- Static variable: totalInstances
- Methods: increment(), decrement(), reset(), getValue()
- Constructor that increments totalInstances
Congratulations! 🎉 You’ve completed the comprehensive guide to Classes and Objects in Java.
Practice these concepts with real code to master Object-Oriented Programming!