Classes and Objects in Java
Last Updated :
21 Jul, 2025
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities.
- A class is a template to create objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects.
- An object is an instance of a class. For example, the animal type Dog is a class, while a particular dog named Tommy is an object of the Dog class.
Java Classes
A class in Java is a template with the help of which we create real-world entities known as objects that share common characteristics and properties.
Here, the below Java code demonstrates the basic use of class in Java. It defines a Student
class with two instance variables (id
and n
), creates an object s1 and prints values of s1.
Java
// File: Student.java
class Student {
int id;
String n;
// Added constructor to initialize both fields
public Student(int id, String n) {
this.id = id;
this.n = n;
}
}
// File: Main.java
public class Main {
public static void main(String[] args) {
// Creating Student object using the new constructor
Student s1 = new Student(10, "Alice");
System.out.println(s1.id);
System.out.println(s1.n);
}
}
Properties of Java Classes
- Class is not a real-world entity. It is just a template or blueprint, or a prototype from which objects are created.
- A class itself does not occupy memory for its attributes and methods until an object is instantiated.
- A Class in Java can contain Data members, methods, a Constructor, Nested classes, and interfaces.
Class Declaration in Java
Java
access_modifier class<class_name> {
data member;
method;
constructor;
nested class;
interface
;
}
Components of Java Classes
In general, class declarations can include these components, in order:
- Modifiers: A class can be public or has default access (Refer this for more details).
- Class keyword: Class keyword is used to create a class.
- Class name: The name should begin with an initial letter (capitalized by convention).
- Superclass (if any): The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
- Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
- Body: The class body is surrounded by braces, { }.
- Fields: Fields are variables defined within a class that hold the data or state of an object.
- Constructors: It is a special method in a class that is automatically called when an object is created. And it's name is same as class name.
Java Objects
Objects are the instances of a class that are created to use the attributes and methods of a class. A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of:
- State: It is represented by attributes of an object. It also reflects the properties of an object.
- Behavior: It is represented by the methods of an object. It also reflects the response of an object with other objects.
- Identity: It gives a unique name to an object and enables one object to interact with other objects.
Java Objects (Example of Dogs)Objects correspond to things found in the real world. For example, a graphics program may have objects such as "circle", "square", and "menu". An online shopping system might have objects such as "shopping cart", "customer", and "product".
Note: Objects (non-primitive types) are always allocated on the heap, while their reference variables are stored on the stack.
Object Instantiation (Declaring Objects)
When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.
Java Object Declaration As we declare variables like (type name). This notifies the compiler that we will use the name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable. So for reference variables , the type must be strictly a concrete class name. In general, we can't create objects of an abstract class or an interface.
Dog tuffy
If we declare a reference variable(tuffy) like this, its value will be undetermined(null) until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object.
Initializing a Java Object
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor.
Java
// Java Program to Demonstrate the
// use of a class with instance variable
// Class Declaration
public class Dog {
// Instance Variables
String name;
String breed;
int age;
String color;
// Constructor Declaration of Class
public Dog(String name, String breed, int age,
String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}
// method 1
public String getName() {
return name;
}
// method 2
public String getBreed() {
return breed;
}
// method 3
public int getAge() {
return age;
}
// method 4
public String getColor() {
return color;
}
@Override public String toString()
{
return ("Name is: " + this.getName()
+ "\nBreed, age, and color are: "
+ this.getBreed() + "," + this.getAge()
+ "," + this.getColor());
}
public static void main(String[] args)
{
Dog tuffy
= new Dog("tuffy", "papillon", 5, "white");
System.out.println(tuffy.toString());
}
}
OutputName is: tuffy
Breed, age, and color are: papillon,5,white
Explanation:
- The Dog class has instance variables for name, breed, age, and color.
- A constructor initializes these variables using passed arguments.
- Constructors have no return type and share the class name.
- Object tuffy is created with: new Dog("tuffy", "papillon", 5, "white").
- toString() returns a string representation of the object.
Dog tuffy = new Dog("tuffy","papillon",5, "white");
The result of executing this statement can be illustrated as :
Note: All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, also called the default constructor. This default constructor calls the class parent's no-argument constructor (as it contains only one statement i.e super();), or the Object class constructor if the class has no other parent (as the Object class is the parent of all classes either directly or indirectly).
Initialize Object by using Method/Function
Java
// Java Program to initialize Java Object
// by using method/function
public class Geeks {
static String name;
static float price;
static void set(String n, float p) {
name = n;
price = p;
}
static void get()
{
System.out.println("Software name is: " + name);
System.out.println("Software price is: " + price);
}
public static void main(String args[])
{
Geeks.set("Visual studio", 0.0f);
Geeks.get();
}
}
OutputSoftware name is: Visual studio
Software price is: 0.0
Ways to Create an Object of a Class
There are four ways to create objects in Java. Although the new keyword is the primary way to create an object, the other methods also internally rely on the new keyword to create instances.
1. Using new Keyword
It is the most common and general way to create an object in Java.
Java
// creating object of class Test
Test t = new Test();
2. Using Reflection (Dynamic Class Loading)
Reflection is a powerful feature in Java that allows a program to inspect and modify its own structure and behavior at runtime.
Java
// Assume Student class exists (or show its definition)
class Student {
public Student() {}
}
public class Main {
public static void main(String[] args) {
try {
Class<?> c = Class.forName("Student");
Student s2 = (Student) c.getDeclaredConstructor().newInstance();
System.out.println("Object created: " + s2);
} catch (ClassNotFoundException e) {
System.err.println("Class not found!");
} catch (NoSuchMethodException e) {
System.err.println("No default constructor!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note: Reflection is used in frameworks like Spring for dependency injection.
3. Using clone() method
The clone() method is present in the Object class. It creates and returns a copy of the object.
Java
// creating object of class Test
Test t1 = new Test();
// creating clone of above object
Test t2 = (Test)t1.clone();
Example:
Java
// Creation of Object
// Using clone() method
// Main class
// Implementing Cloneable interface
class Geeks implements Cloneable {
// Method 1
@Override
protected Object clone()
throws CloneNotSupportedException
{
// Super() keyword refers to parent class
return super.clone();
}
String name = "GeeksForGeeks";
// Method 2
// main driver method
public static void main(String[] args)
{
Geeks o1 = new Geeks();
// Try block to check for exceptions
try {
Geeks o2 = (Geeks)o1.clone();
System.out.println(o2.name);
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
4. Deserialization
De-serialization is a technique of reading an object from the saved state in a file. Refer to Serialization/De-Serialization in Java.
Java
import java.io.*;
class Student implements Serializable {
private String name;
public Student(String name) { this.name = name; }
@Override public String toString()
{
return "Student: " + name;
}
}
public class Main {
public static void main(String[] args)
{
// Serialization
try (ObjectOutputStream out
= new ObjectOutputStream(
new FileOutputStream("student.ser"))) {
out.writeObject(new Student("Alice"));
}
catch (IOException e) {
e.printStackTrace();
}
// Deserialization
try (ObjectInputStream in = new ObjectInputStream(
new FileInputStream("student.ser"))) {
Student s = (Student)in.readObject();
System.out.println(s); // Output: Student: Alice
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Note: The class must implement serializable.
Creating Multiple Objects by one type only (A good practice)
In real-time, we need different objects of a class in different methods. Creating a number of references for storing them is not a good practice and therefore we declare a static reference variable and use it whenever required. In this case, the wastage of memory is less. The objects that are not referenced anymore will be destroyed by the Garbage Collector of Java.
Example:
Java
Test test = new Test();
test = new Test();
In the inheritance system, we use a parent class reference variable to store a sub-class object. In this case, we can switch into different subclass objects using the same referenced variable.
Example:
Java
class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
public class Test {
// using Dog object
Animal obj = new Dog();
// using Cat object
obj = new Cat();
}
Anonymous Objects in Java
Anonymous objects are objects that are instantiated without storing their reference in a variable. They are used for one-time operations (e.g., method calls) and are discarded immediately after use.
- No reference variable: Cannot reuse the object.
- Created & used instantly: Saves memory for short-lived tasks.
- Common in event handling (e.g., button clicks).
Java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) { launch(args); }
@Override public void start(Stage stage)
{
Button button = new Button("Click Me");
button.setOnAction(
event
-> System.out.println(
"Button clicked!")); // Anonymous object via
// lambda
StackPane root = new StackPane(button);
stage.setScene(new Scene(root, 300, 200));
stage.show();
}
}