Prévia do material em texto
Classes and Objects in Java
Last Updated : 27 Mar, 2026
In Java, classes and objects form the foundation of Object-Oriented Programming (OOP). They help model
real-world entities and organize code in a structured way.
A class is a blueprint used to create objects that share common properties and behavior.
An object is an instance of a class. It represents a specific entity created from the class template.
For Example, Dog is a class, Tommy is an object of that class.
Classes and Objects (Here Dog is the Class and Bobby is Object)
Java Class
A class is a blueprint that defines data and behavior for objects. It groups related fields and methods in a
single unit. Memory for instance members is allocated when an object is created, while static members are
allocated when the class is loaded into memory.
Acts as a template to create objects with shared structure.
Does not occupy memory for fields until instantiation.
Can contain fields, methods, constructors, nested classes and interfaces.
class Student {
int id;
String n;
public Student(int id, String n) {
this.id = id;
this.n = n;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(10, "Alice");
System.out.println(s1.id);
Sign In
Courses
Tutorials
Interview Prep
06/08/2026, 10:42 Classes and Objects in Java - GeeksforGeeks
https://www.geeksforgeeks.org/java/classes-objects-java/ 1/8
https://www.geeksforgeeks.org/
Output
10
Alice
Explanation: This code defines a Student class as a blueprint with data members and a constructor to
initialize them. An object s1 is created in main(), which allocates memory and accesses the class fields to
display values.
Java Objects
An object is an instance of a class created to access its data and operations. Each object holds its own state.
State: Values stored in fields.
Behavior: Actions defined through methods.
Identity: Distinguishes one object from another.
Objects mirror real-world items such as customer, product or circle. Non-primitive objects are stored on the
heap while their references remain on the stack.
Java Objects (Example of Dogs)
Object Instantiation
Creating an object is known as instantiation. All instances of a class share structure and behavior while
storing different state values.
Java Object Declaration
Declaration:
System.out.println(s1.n);
}
}
06/08/2026, 10:42 Classes and Objects in Java - GeeksforGeeks
https://www.geeksforgeeks.org/java/classes-objects-java/ 2/8
Dog tuffy;
This only declares a reference. The object is not created and the reference holds null.
Initialization:
tuffy = new Dog("Tuffy", "Papillon", 5, "White");
Initialization
The new operator allocates memory and invokes the constructor.
Example: Defining and Using a Class
public class Dog {
String name;
String breed;
int age;
String color;
public Dog(String name, String breed, int age, String color) {
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}
public String getName() { return name; }
public String getBreed() { return breed; }
public int getAge() { return age; }
public String getColor() { return color; }
@Override
public String toString() {
return "Name is: " + name
+ "\nBreed age and color are: "
+ breed + " " + age + " " + color;
}
public static void main(String[] args) {
Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
System.out.println(tuffy);
}
06/08/2026, 10:42 Classes and Objects in Java - GeeksforGeeks
https://www.geeksforgeeks.org/java/classes-objects-java/ 3/8
Output
Name is: tuffy
Breed age and color are: papillon 5 white
Explanation: This creates a Dog object named tuffy using the Dog constructor inside main(), which initializes
name, breed, age, and color. When System.out.println(tuffy) is executed, the overridden toString() method is
called to display the object’s data.
Note: Every class has at least one constructor. If none is defined Java provides a default no-argument
constructor that calls the parent constructor.
Example: Initialize Object by using Method/Function
Output
}
class Product {
String name;
float price;
// Constructor to initialize object state
public Product(String name, float price) {
this.name = name;
this.price = price;
}
// Setter methods (optional)
public void setName(String name) {
this.name = name;
}
public void setPrice(float price) {
this.price = price;
}
// Getter methods
public String getName() {
return name;
}
public float getPrice() {
return price;
}
}
public class Main {
public static void main(String[] args) {
Product p1 = new Product("Visual Studio", 0.0f);
Product p2 = new Product("IntelliJ IDEA", 4999.0f);
System.out.println(p1.getName() + " - " + p1.getPrice());
System.out.println(p2.getName() + " - " + p2.getPrice());
}
}
06/08/2026, 10:42 Classes and Objects in Java - GeeksforGeeks
https://www.geeksforgeeks.org/java/classes-objects-java/ 4/8
Visual Studio - 0.0
IntelliJ IDEA - 4999.0
Explanation: This code defines a Product class with instance variables name and price, which are initialized
using a constructor. In the main() method, two objects (p1 and p2) are created with different values. Each
object maintains its own state, and the getter methods are used to access and display the values of each
object independently.
Ways to Create Object in Java
Java supports four standard approaches.
1. Using new Keyword
new Keyword is most direct way to create an object.
2. Using Reflection
Used for dynamic class loading as seen in frameworks like Spring.
Output
Student@1dbd16a6
3. Using clone() method
clone() creates a copy of an existing object. The class must implement Cloneable.
// creating object of class Test
Test t = new Test();
class Student {
public Student() {}
}
public class Main {
public static void main(String[] args) {
try {
Class c = Class.forName("Student");
Student s = (Student) c.getDeclaredConstructor().newInstance();
System.out.println(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Geeks implements Cloneable {
String name = "GeeksForGeeks";
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) {
Sign Intorial Advanced Java Interview Questions Exercises Examples Quizzes Projects Cheatsheet DSA in Java Java Co
06/08/2026, 10:42 Classes and Objects in Java - GeeksforGeeks
https://www.geeksforgeeks.org/java/classes-objects-java/ 5/8
https://www.geeksforgeeks.org/java/clone-method-in-java-2/
https://www.geeksforgeeks.org/java/java/
https://www.geeksforgeeks.org/advance-java/advanced-java/
https://www.geeksforgeeks.org/java/java-interview-questions/
https://www.geeksforgeeks.org/java/java-exercises/
https://www.geeksforgeeks.org/java/java-programming-examples/
https://www.geeksforgeeks.org/java/java-quiz/
https://www.geeksforgeeks.org/blogs/java-projects/
https://www.geeksforgeeks.org/java/java-cheat-sheet/
https://www.geeksforgeeks.org/dsa/dsa-in-java/
https://www.geeksforgeeks.org/java/java-collection-tutorial/
Output
GeeksForGeeks
Explanation: Here, creates a new Geeks object g2 by cloning the existing object g1 using the overridden
clone() method. The cloned object copies the field values of g1, which is confirmed by printing g2.name.
4. Using Deserialization
De-serialization is a technique of reading an object from the saved state in a file. Object is recreated from a
stored byte stream.
Output
Student: Alice
Explanation: This first serializes a Student object to the file student.ser using ObjectOutputStream.It then
deserializes the object using ObjectInputStream, recreating the Student object and printing it via the
toString() method.
Anonymous Objects
Anonymous objects are created without a reference and used immediately for one-time operations.
No reference variable: Cannot reuse the object.
try {
Geeks g1 = new Geeks();
Geeks g2 = (Geeks) g1.clone();
System.out.println(g2.name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.*;
class Student implements Serializable {
private String name;
public Student(String name) { this.name = name; }
public String toString() { return "Student: " + name; }
}
public class Main {
public static void main(String[] args) {
try (ObjectOutputStream out =
new ObjectOutputStream(new FileOutputStream("student.ser"))) {
out.writeObject(new Student("Alice"));
} catch (IOException e) { e.printStackTrace(); }
try (ObjectInputStream in =
new ObjectInputStream(new FileInputStream("student.ser"))) {
Student s = (Student) in.readObject();
System.out.println(s);
} catch (Exception e) { e.printStackTrace(); }
}
}
06/08/2026, 10:42 Classes and Objects in Java - GeeksforGeeks
https://www.geeksforgeeks.org/java/classes-objects-java/ 6/8
https://www.geeksforgeeks.org/java/serialization-and-deserialization-in-java/
https://www.geeksforgeeks.org/java/anonymous-object-in-java/
Comment GeeksforGeeks
Explore
Basics
OOP & Interface
Collections
Advance Java Concepts
Practice Java
Courses
Created & used instantly, saves memory for short-lived tasks.
Common in event handling (e.g., button clicks).
new Dog("Max", "Labrador", 3, "Black").getName();
Suggested Quiz 4 Questions
Login to View Explanation 1/4
Which of the following statements about constructors is correct?
A A constructor must have a return type.
B A constructor can have the same name as the class.
C A constructor can be explicitly called like a normal method.
D Constructors can only be used to initialize static variables.
743
Corporate & Communications Address:
A-143, 6th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar
Pradesh (201305)
Registered Address:
Company
About Us
Legal
Privacy
Policy
Contact Us
Advertise
with us
Explore
POTD
Job-A-
Thon
Blogs
Nation
Skill Up
Tutorials
Programming
Languages
DSA
Web
Technology
AI, ML &
Data Science
DevOps
Courses
ML and Data
Science
DSA and
Placements
Web
Development
Programming
Languages
Videos
DSA
Python
Java
C++
Web
Development
Data Science
CS Subjects
Preparation
Corner
Interview
Corner
Aptitude
Puzzles
GfG 160
System Design
06/08/2026, 10:42 Classes and Objects in Java - GeeksforGeeks
https://www.geeksforgeeks.org/java/classes-objects-java/ 7/8
https://www.geeksforgeeks.org/user/Gaurav%20Miglani/
https://www.geeksforgeeks.org/user/Gaurav%20Miglani/
https://www.geeksforgeeks.org/user/Gaurav%20Miglani/
https://www.geeksforgeeks.org/
https://www.geeksforgeeks.org/about/
https://www.geeksforgeeks.org/legal/
https://www.geeksforgeeks.org/legal/privacy-policy/
https://www.geeksforgeeks.org/about/contact-us/
https://www.geeksforgeeks.org/advertise-with-us/
https://www.geeksforgeeks.org/problem-of-the-day
https://practice.geeksforgeeks.org/events/rec/job-a-thon/
https://www.geeksforgeeks.org/category/blogs/?type=recent
https://www.geeksforgeeks.org/nation-skill-up/
https://www.geeksforgeeks.org/computer-science-fundamentals/programming-language-tutorials/
https://www.geeksforgeeks.org/dsa/dsa-tutorial-learn-data-structures-and-algorithms/
https://www.geeksforgeeks.org/web-tech/web-technology/
https://www.geeksforgeeks.org/machine-learning/ai-ml-and-data-science-tutorial-learn-ai-ml-and-data-science/
https://www.geeksforgeeks.org/devops/devops-tutorial/
https://www.geeksforgeeks.org/courses/category/machine-learning-data-science
https://www.geeksforgeeks.org/courses/category/dsa-placements
https://www.geeksforgeeks.org/courses/category/development-testing
https://www.geeksforgeeks.org/courses/category/programming-languages
https://www.geeksforgeeks.org/videos/category/sde-sheet/
https://www.geeksforgeeks.org/videos/category/python/
https://www.geeksforgeeks.org/videos/category/java-w6y5f4/
https://www.geeksforgeeks.org/videos/category/c/
https://www.geeksforgeeks.org/videos/category/web-development/
https://www.geeksforgeeks.org/videos/category/data-science/
https://www.geeksforgeeks.org/videos/category/cs-subjects/
https://www.geeksforgeeks.org/interview-prep/interview-corner/
https://www.geeksforgeeks.org/aptitude/aptitude-questions-and-answers/
https://www.geeksforgeeks.org/aptitude/puzzles/
https://www.geeksforgeeks.org/courses/gfg-160-series
https://www.geeksforgeeks.org/system-design/system-design-tutorial/
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida, Gautam
Buddh Nagar, Uttar Pradesh, 201305
GFG
Corporate
Solution
Campus
Training
Program
CS Core
Subjects
Interview
Preparation
Software and
Tools
DevOps &
Cloud
GATE
Trending
Technologies
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
06/08/2026, 10:42 Classes and Objects in Java - GeeksforGeeks
https://www.geeksforgeeks.org/java/classes-objects-java/ 8/8
https://in.linkedin.com/company/geeksforgeeks
https://www.instagram.com/geeks_for_geeks/
https://twitter.com/geeksforgeeks
https://www.facebook.com/geeksforgeeks.org/
https://www.youtube.com/geeksforgeeksvideos
https://www.geeksforgeeks.org/gfg-corporate-solution/
https://www.geeksforgeeks.org/campus-training-program/
https://www.geeksforgeeks.org/gate/gate-exam-tutorial/
https://www.geeksforgeeks.org/aptitude/interview-corner/
https://www.geeksforgeeks.org/websites-apps/software-and-tools-a-to-z-list/
https://www.geeksforgeeks.org/courses/category/cloud-devops
https://www.geeksforgeeks.org/courses/category/gate
https://www.geeksforgeeks.org/courses/category/trending-technologies/
https://www.geeksforgeeks.org/
https://www.geeksforgeeks.org/copyright-information/
https://geeksforgeeksapp.page.link/gfg-app
https://geeksforgeeksapp.page.link/gfg-app