Classes and Objects in Java
Last Updated :
02 Jan, 2025
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior. For example, the animal type Dog is a class while a particular dog named Tommy is an object of the Dog class. In this article, we will discuss Java classes and objects and how to implement them in our program.
Difference Between Java Classes and Objects
The main differences between class and object in Java are as follows:
Class
| Object
|
|---|
| Class is the blueprint of an object. It is used to create objects. | An object is an instance of the class. |
| No memory is allocated when a class is declared. | Memory is allocated as soon as an object is created. |
| A class is a group of similar objects. | An object is a real-world entity such as a book, car, etc. |
| Class is a logical entity. | An object is a physical entity. |
| A class can only be declared once. | Objects can be created many times as per requirement. |
| An example of class can be a car. | Objects of the class car can be BMW, Mercedes, Ferrari, etc. |
Java Classes
A class in Java is a set of objects which shares common characteristics and common properties. It is a user-defined blueprint or prototype from which objects are created. For example, Student is a class while a particular student named Ravi is an object.
Properties of Java Classes
- Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created.
- Class does not occupy memory.
- Class is a group of variables of different data types and a group of methods.
- A Class in Java can contain:
- Data member
- Method
- Constructor
- Nested Class
- Interface
Class Declaration in 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 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, { }.
Constructors are used for initializing new objects. Fields are variables that provide the state of the class and its objects, and methods are used to implement the behavior of the class and its objects. There are various types of classes that are used in real-time applications such as nested classes, anonymous classes and lambda expressions.
Example 1: Here, the below Java code demonstrates the basic use of class in Java.
Java
// Java Class example
class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String n;
public static void main(String args[]) {
// creating an object of
// Student
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.n);
}
}
Example 2: Here, the below Java code demonstrates creating an object using the newInstance() method.
Java
// Creation of Object
// Using new Instance
class Geeks {
// Declaring and initializing string
String n = "GeeksForGeeks";
// Main driver method
public static void main(String[] args) {
// Try block to check for exceptions
try {
// Correcting the class name to match "Geeks"
Class<?> c = Class.forName("Geeks");
// Creating an object of the main class using reflection
Geeks o = (Geeks) c.getDeclaredConstructor().newInstance();
// Print and display
System.out.println(o.n);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (InstantiationException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Java Objects
An object in Java is a basic unit of Object-Oriented Programming and represents real-life entities. 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.
Example of an object: Dog

Java Objects
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: When we create an object which is a non primitive data type, it’s always allocated on the heap memory.
Declaring Objects (Also called instantiating a Class)
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.
Example:

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.
Example:
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: Here, the above program demonstrate a class Dog with some instance variables. The constructor is used to initializes value to these variables. The toString() method is used to provide a string representation of the dog object. In the main method, a Dog object named tuffy is created with specific values and its details are printed using the toString() method.
This class contains a single constructor. We can recognize a constructor because its declaration uses the same name as the class and it has no return type. The Java compiler differentiates the constructors based on the number and the type of the arguments. The constructor in the Dog class takes four arguments. The following statement provides “tuffy”, “papillon”,5, and “white” as values for those arguments:
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.
Example:
// creating object of class Test
Test t = new Test();
2. Using Class.forName(String className) Method
There is a pre-defined class in java.lang package with name Class. The forName(String className) method returns the Class object associated with the class with the given string name. We have to give a fully qualified name for a class. On calling the new Instance() method on this Class object returns a new instance of the class with the given string name.
// creating object of public class Test
// consider class Test present in com.p1 package
Test obj = (Test)Class.forName(“com.p1.Test”).newInstance();
3. Using clone() method
The clone() method is present in the Object class. It creates and returns a copy of the object.
// 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.
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();
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:
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:
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 but are not stored in a reference variable.
- They are used for immediate method calls.
- They will be destroyed after method calling.
- They are widely used in different libraries. For example, in AWT libraries, they are used to perform some action on capturing an event(eg a key press).
- In the example below, when a key button(referred to by the btn) is pressed, we are simply creating an anonymous object of EventHandler class for just calling the handle method.
btn.setOnAction(new EventHandler()
{
public void handle(ActionEvent event)
{
System.out.println(“Hello World!”);
}
});
Kickstart your Java journey with our online course on Java Programming, covering everything from basics to advanced concepts. Complete real-world coding challenges and gain hands-on experience. Join the Three 90 Challenge—finish 90% in 90 days for a 90% refund. Start mastering Java today!
Similar Reads
Understanding Classes and Objects in Java
The term Object-Oriented explains the concept of organizing the software as a combination of different types of objects that incorporate both data and behavior. Hence, Object-oriented programming(OOPs) is a programming model, that simplifies software development and maintenance by providing some rules. Programs are organized around objects rather t
10 min read
Java.util.Objects class in Java
Java 7 has come up with a new class Objects that have 9 static utility methods for operating on objects. These utilities include null-safe methods for computing the hash code of an object, returning a string for an object, and comparing two objects.Using Objects class methods, one can smartly handle NullPointerException and can also show customized
7 min read
Catching Base and Derived Classes as Exceptions in C++ and Java
An Exception is an unwanted error or hurdle that a program throws while compiling. There are various methods to handle an exception which is termed exceptional handling. Let's discuss what is Exception Handling and how we catch base and derived classes as an exception in C++: If both base and derived classes are caught as exceptions, then the catc
4 min read
Sorting Elements of Arrays and Wrapper Classes that Already Implements Comparable in Java
Java provides the Comparable interface to sort objects using data members of the class. The Comparable interface contains only one method compareTo() that compares two objects to impose an order between them. It returns a negative integer, zero, or positive integer to indicate if the input object is less than, equal to, or greater than the current
4 min read
Private Constructors and Singleton Classes in Java
Let's first analyze the following question: Can we have private constructors ? As you can easily guess, like any method we can provide access specifier to the constructor. If it's made private, then it can only be accessed inside the class. Do we need such 'private constructors ' ? There are various scenarios where we can use private constructors.
2 min read
Java Unnamed Classes and Instance Main Methods
Java has introduced a significant language enhancement in Java Enhancement Proposal (JEP) 445, titled "Unnamed Classes and Instance Main Methods". This proposal aims to address the needs of beginners, making Java more accessible and less intimidating. Let's delve into the specifics of this proposal and understand how it simplifies the learning curv
7 min read
Commonly Used Methods in LocalDate, LocalTime and LocalDateTime Classes in Java
Java provides the three most important classes related to dates namely LocalDate, LocalTime, LocalDateTime which makes the handling of dates in Java very easy as in order to use these classes, we need to import 'java.time' package which is main the main API for dates, times, instants, and durations. Illustration: 1. java.time.* // To include all cl
5 min read
Output of Java program | Set 15 (Inner Classes)
Prerequisite :- Local inner classes , anonymous inner classes 1) What is the output of the following java program? Java public class Outer { public static int temp1 = 1; private static int temp2 = 2; public int temp3 = 3; private int temp4 = 4; public static class Inner { private static int temp5 = 5; private static int getSum() { return (temp1 + t
3 min read
How to Access Inner Classes in Java?
In Java, inner class refers to the class that is declared inside class or interface which were mainly introduced, to sum up, same logically relatable classes as Java is purely object-oriented so bringing it closer to the real world. It is suggested to have adequate knowledge access the inner class, first create an object of the outer class after th
3 min read
Static Control Flow with Inherited Classes in Java
Before understanding the static control flow of a program, we must be familiar with the following two terms: Class loading: It refers to reading the .class file and loading it into the memory(JVM). Java loads classes dynamically, that is, classes are loaded on demand only when they are referred.Class initialization: It refers to executing and initi
6 min read