Module 2:
Introducing Classes:
● Class Fundamentals
● Declaring Objects
● Assigning Object Reference Variables
● Introducing Methods
● Constructors
● The this Keyword
● Garbage Collection.
Methods and Classes:
● Overloading Methods
● Objects as Parameters
● Argument Passing
● Returning Objects
● Recursion
● Access Control
● Understanding static
● Introducing final
● Introducing Nested and Inner
What is a Class in Java?
A class in Java is a blueprint, template, or user-defined data type that describes the properties
(data/fields) and behaviors (methods) that its objects will have.
Think of it like a blueprint for a house the blueprint itself isn’t a house, but you can create many
houses (objects) from that blueprint.
class ClassName {
// Data Members (fields/variables)
// Member Functions (methods)
}
Example
class Car {
// Fields / Data members
String color;
String model;
int speed;
// Method / Behavior
void accelerate() {
speed += 10;
[Link]("Speed increased to " + speed);
}
void brake() {
speed -= 10;
[Link]("Speed reduced to " + speed);
}
}
What is an Object?
An object is an instance of a class.
It’s created using the new keyword and represents a real entity that has state and behavior.
public class Main {
public static void main(String[] args) {
// Object creation
Car car1 = new Car();
// Assign values
[Link] = "Red";
[Link] = "Tesla";
[Link] = 0;
// Access methods
[Link]();
[Link]();
}
}
Structure of a Java Class
Component Description Example
Class Declaration Declares the class with class keyword class Student { ... }
Fields / Attributes Represent data/state of the object int rollNo; String name;
Methods Define behavior/actions void display() { ... }
Constructors Initialize objects Student() { ... }
Access Modifiers Control visibility (public, private, etc.) private int age;
Nested Classes Classes defined inside another class class Inner { }
Static Members Belong to class, not to objects static int count;
Constructor
A constructor is a special method used to initialize an object when it is created.
Rules:
● The constructor name must be the same as the class name.
● It has no return type, not even void.
● It is automatically called when the object is created.
● You can overload constructors (have multiple with different parameters).
class ClassName {
// Constructor
ClassName() {
// initialization code
}
Default Constructor
A default constructor is one that:
Takes no parameters.
Is automatically provided by the compiler if you don’t define any constructor.
Initializes all instance variables to default values:
numeric → 0
boolean → false
object references → null
class Student {
int id;
String name;
// Default constructor
Student() {
id = 1;
name = "Shilpa";
}
void display() {
[Link](id + " " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
[Link](); // Output: 1 Shilpa
}
}
Parameterized Constructor
A parameterized constructor is one that takes parameters to initialize an object with specific
values.
It gives flexibility to assign unique data to each object during creation.
class Student {
int id;
String name;
// Parameterized constructor
Student(int i, String n) {
id = i;
name = n;
}
void display() {
[Link](id + " " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(101, "Riya");
Student s2 = new Student(102, "Amit");
[Link](); // Output: 101 Riya
[Link](); // Output: 102 Amit
}
}
Overloading Constructors
You can define multiple constructors in the same class with different parameter lists.
This is called constructor overloading.
class Student {
int id;
String name;
Student() {
id = 0;
name = "Unknown";
}
Student(int i, String n) {
id = i;
name = n;
}
void display() {
[Link](id + " " + name);
}
}
Copy Constructor
A copy constructor is used to create a new object by copying data from another existing object.
Java doesn’t provide a built-in copy constructor (unlike C++), but you can define your own.
class Student {
int id;
String name;
// Parameterized constructor
Student(int i, String n) {
id = i;
name = n;
}
// Copy constructor
Student(Student s) {
id = [Link];
name = [Link];
}
void display() {
[Link](id + " " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(101, "Shilpa");
Student s2 = new Student(s1); // invoking copy constructor
[Link](); // 101 Shilpa
[Link](); // 101 Shilpa
}
}
Difference
Feature Default Parameterized Copy Constructor
Constructor Constructor
Parameters None One or more Object of same class
Purpose To assign default To assign custom To copy values from
values values another object
Provided by Yes (if none No No
Compiler defined)
Example Student() Student(int id, String Student(Student s)
name)
What is this in Java?
The this keyword is a reference variable in Java that refers to the current object of the class the
one whose method or constructor is being invoked.
class Student {
int id;
String name;
void setData(int id, String name) {
[Link] = id;
[Link] = name;
}
void display() {
[Link](id + " " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
[Link](101, "Shilpa");
[Link](); // Output: 101 Shilpa
}
}
Without this, What Happens?
void setData(int id, String name) {
id = id;
name = name;
}
This would not work properly, because:
● Both instance variables and parameters have the same name.
● Java assumes you’re referring to the local variables (id, name inside the method), not the
instance ones.
● Hence, the instance variables remain uninitialized (default values).
Using [Link] = id; clarifies that you are assigning the method parameters to the instance
variables.
What is Garbage Collection (GC)?
Garbage Collection in Java is the process of automatically freeing memory by deleting
objects that are no longer reachable or used by any part of the program.
Example:
class Demo {
int value;
}
public class Main {
public static void main(String[] args) {
Demo d1 = new Demo(); // object 1 created
d1 = new Demo(); // object 2 created, object 1 becomes unreachable
}
}
After line 2, the first object (new Demo()) no longer has any reference so it becomes eligible for
garbage collection.
Why Garbage Collection?
Java runs inside the JVM (Java Virtual Machine), which manages memory in two main areas:
● Stack – for method calls and local variables
● Heap – for objects (created using new)
When you no longer need an object, you don’t have to free() it manually like in C.
The Garbage Collector (GC) automatically removes it from the heap when it becomes
unreachable.
When Does an Object Become Eligible for Garbage Collection?
An object becomes eligible for GC when no live thread has any reference to it.
What is Method Overloading?
Method Overloading means having multiple methods in the same class with the
same name but different parameters
(i.e. different number, type, or order of parameters).
It allows you to reuse the same method name for similar actions.
Rules of Overloading
Two or more methods are considered overloaded if:
1. They have the same method name.
2. They have different parameter lists (number, type, or order).
3. They may have different return types (but return type alone can’t distinguish overloaded
methods).
class Calculator {
// Method 1 - adds two integers
int add(int a, int b) {
return a + b;
}
// Method 2 - adds three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Method 3 - adds two double values
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]([Link](5, 10)); // calls method 1 → 15
[Link]([Link](5, 10, 15)); // calls method 2 → 30
[Link]([Link](2.5, 3.5)); // calls method 3 → 6.0
}
}
Objects as Parameters in Java?
In Java, you can pass objects as arguments to methods just like primitive types (int, double,
etc.).
When you do this, you are actually passing the reference (address) of the object not the actual
object itself.
That means:
● The method can access the object’s data members.
● If the method modifies the object’s fields, the changes will reflect outside the method too
(since both refer to the same object in memory).
class Student {
int id;
String name;
// Constructor
Student(int i, String n) {
id = i;
name = n;
}
}
public class Main {
static void showDetails(Student s) {
[Link]("ID: " + [Link]);
[Link]("Name: " + [Link]);
}
public static void main(String[] args) {
Student s1 = new Student(101, "Shilpa");
showDetails(s1); // Passing object as argument
}
}
Return Object
class Employee {
int id;
String name;
float sal;
// Constructor
Employee()
{
id=0;
name="default";
sal=1000;
}
Employee(int i, String n,float s) {
id = i;
name = n;
sal = s;
}
}
public class Main {
static Employee incrementsal(Employee e) {
Employee temp = new Employee();
[Link] = [Link]+1000;
return temp;
}
static void showDetails(Employee s) {
[Link]("ID: " + [Link]);
[Link]("Name: " + [Link]);
[Link]("Salary: " + [Link]);
}
public static void main(String[] args) {
Employee e1 = new Employee(101, "Shilpa",1000);
showDetails(e1); // Passing object as argument
Employee e2 = incrementsal(e1); //returned an employee object
showDetails(e2);
}
}
What is Recursion?
Recursion is a process where a method calls itself either directly or indirectly, until a
certain base condition is met.
In simple words :
A function calling itself again and again until it reaches a stopping point.
Example Idea
Think of recursion like standing between two mirrors you see an infinite reflection of yourself.
But in programming, we add a base case to stop it from going infinite!
Basic Structure
void recursiveMethod() {
// base condition (to stop recursion)
if (condition)
return;
// recursive call
recursiveMethod();
}
Example:
class Demo {
static void printNumbers(int n) {
if (n == 0)
return; // base case (stopping condition)
[Link](n);
printNumbers(n - 1); // recursive call
}
public static void main(String[] args) {
printNumbers(5);
}
}
Output
5
4
3
2
1
Example 2 — Factorial Using Recursion
Factorial:
n! = n × (n-1) × (n-2) × ... × 1
class Factorial {
static int fact(int n) {
if (n == 1) // base case
return 1;
else
return n * fact(n - 1); // recursive call
}
public static void main(String[] args) {
[Link](fact(5)); // 120
}
}
What is Access Control in Java?
Access control in Java means restricting or allowing access to classes, methods,
variables, and constructors from other classes or packages.
It’s Java’s built-in security mechanism that controls how data and methods are exposed to other
parts of a program.
Access control is implemented using access modifiers.
Why Access Control?
Access control supports Encapsulation, one of the four OOP principles.
Encapsulation =
● Wrapping data (fields) and code (methods) into a single unit (class)
and restricting direct access to that data.
Benefits:
● Protects data from unintended modification
● Controls what’s visible to other classes
● Helps maintain clean APIs
● Increases modularity and security
Access Modifiers in Java
Modifier Within Within Subclass (Different Outside
Class Package Package) Package
private ✅ ❌ ❌ ❌
(default) no
modifier
✅ ✅ ❌ ❌
protected ✅ ✅ ✅ ❌
public ✅ ✅ ✅ ✅
private
● Most restrictive access modifier.
● Members are accessible only within the same class.
● Not visible to other classes (even subclasses).
default (package-private)
● When no access modifier is specified.
● Accessible only within the same package.
● Not accessible from classes in different packages.
protected
● Accessible within the same package, and also by subclasses in other packages.
● Used mainly in inheritance.
public
● Least restrictive.
● Accessible from anywhere in the program (same or different package).
What is static in Java?
The static keyword in Java is used to indicate that a member (variable, method,
block, or nested class) belongs to the class itself rather than to a specific object of
that class.
In other words:
● Non-static members → belong to objects (each object has its own copy).
● Static members → belong to the class (shared among all objects).
Why Use static?
Because sometimes you want:
● One common value shared by all objects (e.g., a counter, company name).
● A utility method that does not depend on instance data (like [Link]()).
● To access members without creating an object.
Where Can We Use static?
You can apply static to:
1. Variables (fields)
2. Methods
3. Blocks
4. Nested classes
Static Variables (a.k.a Class Variables)
A static variable belongs to the class, not to any one object.
● All objects share the same copy.
● Memory is allocated only once, when the class is loaded.
Example:
class Student {
int id;
String name;
static String college = "ABC College"; // static variable
Student(int id, String name) {
[Link] = id;
[Link] = name;
}
void display() {
[Link](id + " " + name + " " + college);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(1, "Shilpa");
Student s2 = new Student(2, "Amit");
[Link]();
[Link]();
[Link] = "XYZ Institute"; // changing static variable
[Link]();
[Link]();
}
}
Output:
—--------------
1 Shilpa ABC College
2 Amit ABC College
1 Shilpa XYZ Institute
2 Amit XYZ Institute
Static Methods
● Belong to the class, not the object.
● Can be called without creating an object.
● Can access only static members directly (not instance variables).
class MathUtil {
static int square(int x) { // static method
return x * x;
}
}
public class Main {
public static void main(String[] args) {
// No object creation needed
[Link]("Square of 5: " + [Link](5));
}
}
Static Nested Classes
A static nested class is a class defined inside another class with the static keyword.
● It can be accessed without creating an object of the outer class.
● It cannot access non-static members of the outer class directly.
class Outer {
static int outerValue = 100;
static class Inner {
void show() {
[Link]("Accessing static variable from outer: " + outerValue);
}
}
}
public class Main {
public static void main(String[] args) {
[Link] obj = new [Link](); // no Outer object needed
[Link]();
}
}
final Variable (Constant)
When a variable is declared as final, its value cannot be changed once assigned.
class ExampleFinalVariable {
public static void main(String[] args) {
final int MAX_VALUE = 100;
[Link]("Max Value: " + MAX_VALUE);
// MAX_VALUE = 200; // Error: cannot assign a value to final variable
}
}
final Method
When a method is declared as final, it cannot be overridden by subclasses.
class Parent {
final void display() {
[Link]("This is a final method from Parent class");
}
}
class Child extends Parent {
// void display() { } // Error: cannot override final method
}
public class ExampleFinalMethod {
public static void main(String[] args) {
Child obj = new Child();
[Link](); // Works fine, inherited but not overridden
}
}
final Class
When a class is declared as final, it cannot be inherited.
final class Vehicle {
void start() {
[Link]("Vehicle started");
}
}
// class Car extends Vehicle { } // Error: cannot subclass final class
public class ExampleFinalClass {
public static void main(String[] args) {
Vehicle v = new Vehicle();
[Link]();
}
}
What is a Nested Class in Java?
A nested class is a class defined inside another class.
It’s used to logically group classes that are only used in one place and to improve encapsulation
(data hiding).
Why use nested classes?
● To keep related classes together for better organization.
● To make helper classes private to the outer class.
● To access members of the outer class easily.
class OuterClass {
private String outerMsg = "Message from Outer Class";
// Static Nested Class
static class StaticNested {
void display() {
[Link]("Inside Static Nested Class");
}
}
// 2Non-static Inner Class
class Inner {
void show() {
[Link]("Accessing: " + outerMsg);
}
}
}
public class Main {
public static void main(String[] args) {
// Accessing static nested class
[Link] staticObj = new [Link]();
[Link]();
// Accessing inner (non-static) class → needs outer object
OuterClass outer = new OuterClass();
[Link] innerObj = [Link] Inner();
[Link]();
}
}
Types of Nested Classes
Type Definition Can Access Outer Needs Outer
Members? Object?
Static Nested Class Declared using static Only static members ❌ No
Non-static Inner Class Declared inside a class (no All members (even
static) private)
✅ Yes
Local Inner Class Declared inside a method Local variables
(effectively final)
✅ Yes
Anonymous Inner
Class
Class without a name,
declared inline
All outer members ✅ Yes
Why Use Nested Classes?
Reason Explanation
Logical grouping Helps keep related classes together (e.g., [Link] in Java
Collections).
Encapsulation Can hide helper classes from external access.
Readability Keeps code cleaner and more modular.
Tighter coupling Inner classes can naturally access outer class data without
getters/setters.