Objects in Java (Explained with Examples)
What is an Object in Java?
An object is a real-world entity created from a class.
It represents the actual implementation of a class.
If a class is a blueprint, an object is the thing built from it.
Example (Real Life)
• Class → Student
• Object → Alice, Brian
Why Objects are Important
Objects allow us to:
✔ Store data
✔ Call methods
✔ Represent real-world things
✔ Use OOP concepts like encapsulation and inheritance
How to Create an Object in Java
Syntax
ClassName objectName = new ClassName();
Example
class Student {
int id;
String name;
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // object created
[Link] = 101;
[Link] = "Alice";
[Link]([Link]);
[Link]([Link]);
}
Object Using Methods
class Student {
int id;
String name;
void display() {
[Link](id + " " + name);
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
[Link] = 1;
[Link] = "Brian";
[Link](); // method called using object
Object Using Constructor
class Student {
int id;
String name;
Student(int i, String n) {
id = i;
name = n;
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(1, "Alice");
Student s2 = new Student(2, "Brian");
[Link]([Link]);
[Link]([Link]);
Multiple Objects of One Class
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
Each object:
• Has its own memory
• Has different values
Object Memory Allocation
• Object is stored in heap memory
• Reference variable (s1) is stored in stack memory
Student s1 = new Student();
Anonymous Object
Object created without reference name.
new Student().display();
Used when:
✔ Object is needed only once
Object vs Class (Very Common Exam Question)
Class Object
Blueprint Real entity
Logical Physical
No memory Memory allocated
Defined once Can be many
Object Lifecycle
1. Declaration
2. Instantiation
3. Initialization
4. Garbage collection
Simple Exam Definition (Use This )
An object is an instance of a class that represents a real-world entity and occupies memory in the
heap.
Real-World Example
class Car {
String brand;
int speed;
void drive() {
[Link]("Car is driving");
Car c1 = new Car();
[Link] = "Toyota";
[Link] = 120;
[Link]();