Objects, Classes, and Constructors in Java
Objects, Classes, and Constructors in Java
Simple Definition:
A class is a blueprint or template for creating objects. It defines what an object will look like and
what it can do.
Analogy 1 — Blueprint of a House : A class is like an architect's blueprint. The blueprint itself is
not a house — but you can build many houses FROM that blueprint. Each house built = an object.
Analogy 2 — Cookie Cutter : Class = Cookie cutter (the mold) Object = The actual cookie made
from the mold You can make many cookies from one cutter!
❖ Class
▪ Fields/Variables (Attributes) → What the object HAS
Example: color, speed, name
▪ Methods (Beha––viors) → What the object DOES
Example: drive(), stop(), accelerate()
Syntax of a Class:
class ClassName {
// Fields (attributes/variables)
dataType fieldName;
// Methods (behaviors)
returnType methodName(parameters) {
// method body
}
}
void stop() {
[Link](brand + " has stopped.");
}
}
Simple Definition:
An object is a real-world instance (actual entity) created from a class. It has its own copy of the
class's fields and can use its methods.
Analogy: If Car is the blueprint, then myCar, yourCar, taxiCar are actual objects (real cars) built from
that blueprint.
// Example:
Car myCar = new Car();
speed = 0
Complete Example:
class Car {
String color;
String brand;
int speed;
void drive() {
[Link](brand + " (" + color + ") driving at " +
. speed + " km/h");
}
}
class Main {
public static void main(String[] args) {
// Creating objects
Car car1 = new Car();
[Link] = "Red";
[Link] = "Toyota";
[Link] = 80;
[Link](); // Output: Toyota (Red) driving at 80 km/h
Key Point: Each object has its own separate copy of instance variables. [Link] and [Link]
are independent!
Quick Summary:
Practice Questions:
3. Can two objects of the same class have different values for their fields? Explain.
Method Structure:
accessModifier returnType methodName(parameterList) {
// method body
return value; // only if returnType ≠ void
}
// Calling:
Greeter g = new Greeter();
[Link]();
class Calculator {
void printSum(int a, int b) {
[Link]("Sum = " + (a + b));
}
}
// Calling:
Calculator c = new Calculator();
[Link](5, 3); // Output: Sum = 8
class Calculator {
int add(int a, int b) {
return a + b; // returns the result
}
}
// Calling:
Calculator c = new Calculator();
int result = [Link](10, 20);
[Link](result); // Output: 30
2.5 Overloading Methods
Definition:
Method Overloading means having multiple methods with the SAME name but different
parameter lists (different number, type, or order of parameters) within the same class.
Analogy: Think of a Swiss Army Knife — one tool, but it can do many things (cut, open bottle, file
nails). Same name (knife), different functionality.
Real-life: A print() method that can print integers, strings, doubles — you call print() every time but it
behaves differently based on what you pass.
Access modifier
class Main {
public static void main(String[] args) {
MathOperations m = new MathOperations();
[Link]([Link](3, 4)); // 7 (int version)
[Link]([Link](3.5, 4.5)); // 8.0 (double version)
[Link]([Link](1, 2, 3)); // 6 (3-param version)
}
}
How Java decides which method to call? This is called compile-time polymorphism or static
binding — the compiler looks at the arguments and decides at compile time.
Quick Summary:
Practice Questions:
2. Can two methods have the same name and same parameters but different return types? Why?
3. Write a class with an overloaded method area() that calculates area of square, rectangle, and
circle.
PART 3: Constructors
Simple Definition:
A constructor is a special method that is automatically called when an object is created using new.
Its purpose is to initialize the object.
Analogy — Hospital Birth Registration : When a baby is born (object created), immediately the
hospital registers the birth — name, date, weight (initialization). This automatic registration =
constructor!
Analogy 2 — New Phone Setup : When you first turn on a new phone (create object), it
automatically runs a setup process (constructor) — setting language, date, etc.
Properties of Constructor:
Property Value
Basic Example:
class Student {
String name;
int age;
// Constructor
Student() {
name = "Unknown";
age = 0;
[Link]("Student object created!");
}
}
class Main {
public static void main(String[] args) {
Student s = new Student(); // Constructor called automatically
// Output: Student object created!
}
}
Three Types:
I. Constructors
1. Default Constructor
2. No-Argument Constructor (No-arg)
3. Parameterized Constructor
Definition: When you do NOT write any constructor in a class, Java automatically provides an
invisible, empty constructor. This is called the default constructor.
class Animal {
String name;
// No constructor written by programmer
// Java automatically adds:
// Animal() { } ← invisible default constructor
}
Important: If you write ANY constructor yourself, Java stops providing the default constructor!
Definition: A constructor that accepts parameters to initialize the object with specific values.
class Student {
String name;
int age;
double marks;
// Parameterized constructor
Student(String n, int a, double m) {
name = n;
age = a;
marks = m;
}
void display() {
[Link]("Name: " + name + ", Age: " + age + ", Marks:
" + marks);
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student("Alice", 20, 85.5);
Student s2 = new Student("Bob", 21, 90.0);
Just like method overloading, we can have multiple constructors in the same class with different
parameter lists.
class Rectangle {
int length;
int width;
// No-arg constructor
Rectangle() {
length = 1;
width = 1;
}
// Two parameters
Rectangle(int l, int w) {
length = l;
width = w;
}
int area() {
return length * width;
}
}
class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(); // 1x1
Rectangle r2 = new Rectangle(5); // 5x5
Rectangle r3 = new Rectangle(4, 6); // 4x6
[Link]([Link]()); // 1
[Link]([Link]()); // 25
[Link]([Link]()); // 24
}
}
Return type None (not even void) Must have (void or other)
7-Mark Question: "Explain types of constructors with examples and compare constructor vs
method."
Quick Summary:
Practice Questions:
An array of objects is an array where each element is an object reference (instead of a primitive
value).
Memory Diagram:
│ │ │
▼ ▼ ▼
Complete Example:
class Student {
String name;
int age;
Student(String n, int a) {
name = n;
age = a;
}
void display() {
[Link]("Name: " + name + ", Age: " + age);
}
}
class Main {
public static void main(String[] args) {
// Array of 3 Student objects
Student[] students = new Student[3];
Output:
Name: Alice, Age: 20
Name: Bob, Age: 21
Name: Charlie, Age: 19
Definition:
Method Binding refers to the process of connecting a method call to the method body (deciding
which method gets executed).
Two Types:
• Used for: static methods, private methods, final methods, overloaded methods
class Animal {
static void sound() {
[Link]("Some animal sound");
}
}
// Resolved at compile time → static binding
[Link]();
• Happens at runtime
• JVM determines which method to call based on the actual object type at runtime
class Animal {
void sound() {
[Link]("Generic animal sound");
}
}
class Main {
public static void main(String[] args) {
Animal a = new Dog(); // Animal reference, Dog object
[Link](); // Which sound()? Decided at RUNTIME → "Woof!"
// This is dynamic binding!
}
}
Analogy: Static binding = Reading from a book (decided in advance). Dynamic binding = Asking
someone a question and they answer based on who they actually are at that moment.
Definition:
Method Overriding occurs when a child class provides its own specific implementation of a
method that is already defined in the parent class.
Analogy — Recipe Customization : A parent class has a makeFood() method that makes basic
food. A child class (Italian Restaurant) overrides it to make pizza specifically. Same method name,
but different behavior!
Rule Detail
Example:
class Shape {
void draw() {
[Link]("Drawing a generic shape");
}
double area() {
return 0;
}
}
Circle(double r) {
radius = r;
}
@Override
void draw() {
@Override
double area() {
return 3.14 * radius * radius;
}
}
Rectangle(double l, double w) {
this.l = l;
this.w = w;
}
@Override
void draw() {
class Main {
public static void main(String[] args) {
Shape s1 = new Circle(5);
Shape s2 = new Rectangle(4, 6);
[Link]([Link]()); // 78.5
[Link]([Link]()); // 24.0
}
}
An exception is an unwanted event that occurs during program execution and disrupts the normal
flow.
Analogy — Traffic Accident : You're driving normally (program running). Suddenly there's an
accident (exception). If you have no plan, traffic stops (program crashes). But if there's a traffic control
system (exception handling), traffic is redirected (program continues).
Common Exceptions:
Exception Cause
Quick Summary:
Practice Questions:
In Java, you can pass an object as an argument to a method, just like you pass primitive values.
Important: Java passes the reference (address) of the object, not a copy of the object itself. So any
changes made inside the method WILL affect the original object!
class Student {
String name;
int marks;
Student(String n, int m) {
name = n;
marks = m;
}
class Temperature {
double celsius;
Temperature(double c) {
celsius = c;
}
void display() {
[Link]("Temperature: " + celsius);
}
}
class Main {
public static void main(String[] args) {
Temperature t1 = new Temperature(100); // 100°C
Temperature t2 = [Link](); // returns new object
Static Variables:
Definition: A static variable is shared among ALL objects of a class. It belongs to the class itself, not
to any individual object.
class Student {
String name; // instance variable (each object has its own)
static int count = 0; // static variable (SHARED by all objects)
Student(String n) {
name = n;
count++; // increment shared counter whenever new student
created
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
Student s3 = new Student("Charlie");
[Link]("Total students: " + [Link]); // 3
// Access static variable using CLASS NAME (not object name)
}
}
Static Methods:
Definition: A static method belongs to the class, not to objects. Can be called without creating an
object.
class MathUtils {
static int square(int n) {
return n * n;
}
class Main {
public static void main(String[] args) {
// No need to create object!
[Link]([Link](5)); // 25
[Link]([Link](3)); // 27
}
}
Can do Cannot do
Why is main() static? Because JVM needs to call main() WITHOUT creating any object first!
Static vs Instance Members:
Definition:
Access modifiers are keywords that control the visibility/accessibility of classes, variables, and
methods.
Modifier Same Class Same Package Subclass (different package) Other Package
public
protected
private
Visualization:
Example:
class Person {
public String name; // accessible everywhere
protected int age; // accessible in package + subclasses
String city; // default - accessible in same package
only
private String password; // accessible ONLY in this class
// Getter
public double getBalance() {
return balance;
}
// Setter with validation
public void setBalance(double amount) {
if (amount >= 0) {
balance = amount;
} else {
[Link]("Invalid amount!");
}
}
}
Best Practice: Make all fields private, provide public getters/setters = Perfect Encapsulation!
7-Mark Question: "Explain access modifiers in Java with examples and an accessibility table."
Definition:
this is a reference to the current object — the object that is currently calling the method or
constructor.
Analogy: When you say "I will do this" — "I" refers to yourself. Similarly, this in Java refers to the
current object itself.
Uses of this:
class Student {
String name;
int age;
Rectangle() {
this(1, 1); // calls Rectangle(int, int) constructor
}
Rectangle(int l, int w) {
[Link] = l;
[Link] = w;
}
}
class Printer {
void print(Student s) {
[Link]("Printing: " + [Link]);
}
}
class Student {
String name = "Alice";
void sendToPrint(Printer p) {
[Link](this); // passing current object
}
}
Definition:
Garbage Collection is Java's automatic memory management system that removes objects from
heap memory that are no longer being referenced/used.
Analogy — Automatic Room Cleaning Robot : Imagine a robot that automatically cleans your
room by removing things you no longer use (unused objects). You don't need to manually clean — Java
does it for you!
// Case 2: Re-assignment
Student s = new Student("Alice");
s = new Student("Bob"); // Alice object lost reference → eligible for
GC
• Garbage collection happens automatically (you can suggest but not force it)
Definition:
finalize() is a method that the JVM calls on an object just before garbage collecting it. It gives the
object a chance to clean up resources (close files, database connections, etc.).
Analogy — Last Will Before Departure : Before someone leaves (object destroyed), they write a
will/leave instructions. finalize() is Java's "last will" — execute this before I'm destroyed!
class DatabaseConnection {
String connectionName;
DatabaseConnection(String name) {
[Link] = name;
[Link]("Connection opened: " + name);
}
@Override
protected void finalize() throws Throwable {
[Link]("Connection closed: " + connectionName);
// cleanup code here
[Link]();
}
}
class Main {
public static void main(String[] args) {
DatabaseConnection db = new DatabaseConnection("DB1");
db = null; // eligible for GC
[Link](); // request GC
// finalize() may be called before object is collected
}
}
Note: finalize() is deprecated since Java 9 — not recommended for use. Better to use try-with-
resources or close() methods.
Definition:
A class defined inside another class is called a nested class. The outer class is called the Enclosing
class.
Analogy — File inside a Folder : Just as you can have a file (inner class) inside a folder (outer
class), Java allows classes inside classes.
1. Nested Classes
a. Static Nested Class
b. Non-Static (Inner Classes)
i. Regular Inner Class
ii. Method Local Inner Class
iii. Anonymous Inner Class
class Outer {
int x = 10; // instance variable
class Inner {
void display() {
[Link]("Inner class: x = " + x);
// Can access ALL members of outer class
}
}
}
class Main {
public static void main(String[] args) {
// Must create outer object first
Outer outer = new Outer();
[Link] inner = [Link] Inner(); // special syntax
[Link](); // Inner class: x = 10
}
}
A class without a name, defined and instantiated in one expression. Used for one-time use.
// Typically used with interfaces or abstract classes
interface Greeting {
void greet();
}
class Main {
public static void main(String[] args) {
// Anonymous class implementing Greeting interface
Greeting g = new Greeting() {
@Override
public void greet() {
[Link]("Hello from anonymous class!");
}
};
[Link]();
}
}
Definition:
String is a class in Java (not a primitive type!) that represents a sequence of characters. Strings in
Java are immutable — once created, they cannot be changed.
Analogy — Engraved Stone Tablet : Once words are engraved in stone (String created), you can't
change them. But you can create a NEW stone with different words. That's string immutability!
Creating Strings:
String Pool:
┌────────────────┐
└────────────────┘
String s1 = "Hello";
String s3 = "Hello";
// s1 and s3 point to SAME object in string pool (memory efficient!)
String s = "Hello";
StringBuilder vs String:
String a = "hello";
String b = new String("hello");
[Link](a == b); // false (comparing references)
Quick Summary:
Practice Questions:
2) CONSTRUCTORS
i) Default → Auto-provided by Java (if no constructor written)
ii) No-arg → Programmer written, no parameters
iii) Parameterized → Takes parameters for initialization
iv) Overloaded → Multiple constructors, different parameters
★ No return type | Same name as class | Called by new
4) BINDING
i) Static/Early → Compile time (overloading, static, private, final)
ii) Dynamic/Late → Runtime (overriding)
5) ACCESS MODIFIERS
i) public → Everywhere
ii) protected → Same package + subclass
iii) default → Same package only
iv) private → Same class only
★ private < default < protected < public
6) this KEYWORD
i) Refers to current object
ii) Resolves name conflicts ([Link] = param)
iii) this() → calls another constructor
iv) Can pass/return current object
7) GARBAGE COLLECTION
i) Automatic memory management by JVM
ii) Removes unreferenced heap objects
iii) finalize() → called before object is GC'd (deprecated)
iv) [Link]() → requests GC (not guaranteed)
8) NESTED CLASSES
i) Static Nested → No outer instance needed
ii) Inner Class → Can access outer instance members
iii) Anonymous → One-time, nameless class
9) STRING CLASS
i) Immutable (cannot change once created)
ii) String Pool for literals
iii) Use equals() not == for comparison
iv) StringBuilder for mutable strings
1. Explain all types of constructors in Java with examples and difference from methods.
2. Explain method overloading and method overriding with examples. Tabulate the
differences.
3. What are access modifiers in Java? Explain each with examples and accessibility table.
4. Explain static members in Java. How are static variables different from instance
variables? Give programs.
5. Explain the String class in Java with at least 8 important methods and examples.
Mistake Correction
Forgetting this() must be first in constructor this() MUST be the first statement
Not initializing array elements after creating new Student[3] creates refs, not objects — must create
array each
Accessing static variable via object name Access via class name: [Link]