What is an Object in Java?
An object is an instance of a class. When a class is defined, no memory is allocated until you create an object of it.
In simple words: A class is a blueprint, and an object is something built from that blueprint.
How to Create an Object in Java?
ClassName objectName = new ClassName();
ClassName
: The name of the class.objectName
: The variable that holds the object reference.new
: Keyword to create a new object.ClassName()
: Constructor call.
Example 1: Simple Object Creation
class Animal {
void sound() {
System.out.println("Animals make sounds");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // object creation
myAnimal.sound(); // method call
}
}
Output:
Animals make sounds
Example 2: Object with Fields
class Car {
String brand = "Honda";
int speed = 100;
void showDetails() {
System.out.println("Brand: " + brand);
System.out.println("Speed: " + speed + " km/h");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // create object
myCar.showDetails(); // access method
}
}
Output:
Brand: Honda
Speed: 100 km/h
Example 3: Multiple Objects from the Same Class
class Student {
String name;
int age;
void display() {
System.out.println(name + " is " + age + " years old.");
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // 1st object
s1.name = "Alice";
s1.age = 20;
Student s2 = new Student(); // 2nd object
s2.name = "Bob";
s2.age = 22;
s1.display();
s2.display();
}
}
Output:
Alice is 20 years old.
Bob is 22 years old.
Object Terminology
Term | Meaning |
---|---|
Class | Blueprint or template |
Object | Instance of a class |
Fields | Variables in the class |
Methods | Functions/behaviors of the object |
Constructor | Initializes an object |
Memory Allocation
When an object is created using new
, Java allocates memory in heap for that object and returns a reference to it.
Real-Life Example Analogy
Think of a class MobilePhone
as a design.
You can create multiple phones (objects) like Samsung
, iPhone
, OnePlus
— all using the same design but with different values.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.