Understanding Classes and Objects in Java
Last Updated :
11 Jul, 2025
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 than action and logic. It increases the flexibility and maintainability of the program. Understanding the working of the program becomes easier, as OOPs bring data and its behavior (methods) into a single(objects) location.
The basic concepts of OOPs are:
- Object
- Class
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
This article deals with Objects and Classes in Java.
Requirements of Classes and Objects in Object Oriented Programming
Classes: A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. Classes are required in OOPs because:
- It provides the template for creating objects, which can bind code into data.
- It has definitions of methods and data.
- It supports the inheritance property of Object Oriented Programming and hence can maintain the class hierarchy.
- It helps in maintaining the access specifications of member variables.
Objects: It is the basic unit of Object Oriented Programming and it represents real-life entities.
Real-life entities share two characteristics: they all have attributes and behaviour.
An object consists of:
- State: It is represented by attributes of an object. It also shows properties of an object.
- Behavior: It is represented by methods of an object. It shows response of an object with other objects.
- Identity: It gives a unique name to an object. It also grants permission to one object to interact with other objects.
Objects are required in OOPs because they can be created to call a non-static function which are not present inside the Main Method but present inside the Class and also provide the name to the space which is being used to store the data.
Example : For addition of two numbers, it is required to store the two numbers separately from each other, so that they can be picked and the desired operations can be performed on them. Hence creating two different objects to store the two numbers will be an ideal solution for this scenario.
Example to demonstrate the use of Objects and classes in OOPs

Objects relate to things found in the real world. For example, a graphics program may have objects such as "circle", "square", "menu". An online shopping system might have objects such as "shopping cart", "customer", and "product".
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 :

As we declare variables like (type name;). This notifies the compiler that we will use 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 variable, 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 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 an Object using new
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 illustrate the concept
// of classes and objects
// 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 ("Hi my name is " + this.getName() +
".\nMy breed, 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());
}
}
OutputHi my name is tuffy.
My breed, age and color are papillon, 5, white
- 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, "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 contain only one statement i.e super();), or the Object class constructor if the class has no other parent (as Object class is parent of all classes either directly or indirectly).
Different ways to create Objects
- Using new keyword: It is the simplest way to create object. By using this method, the desired constructor can be called.
Syntax:
ClassName ReferenceVariable = new ClassName();
Java
// Java program to illustrate the
// creating and accessing objects
// using new keyword
// base class
class Dog {
// the class Dog has two fields
String dogName;
int dogAge;
// the class Dog has one constructor
Dog(String name, int age)
{
this.dogName = name;
this.dogAge = age;
}
}
// driver class
public class Test {
public static void main(String[] args)
{
// creating objects of the class Dog
Dog ob1 = new Dog("Bravo", 4);
Dog ob2 = new Dog("Oliver", 5);
// accessing the object data through reference
System.out.println(ob1.dogName + ", " + ob1.dogAge);
System.out.println(ob2.dogName + ", " + ob2.dogAge);
}
}
- Using Class.newInstance() method: It is used to create new class dynamically. It can invoke any no-argument constructor. This method return class Class object on which newInstance() method is called, which will return the object of that class which is being passed as command line argument.
Reason for different exceptions raised:-
ClassNotFoundException will occur if the passed class doesn’t exist.
InstantiationException will occur, if the passed class doesn’t contain default constructor as newInstance() method internally calls the default constructor of that particular class.
IllegalAccessException will occur, if the driving class doesn’t has the access to the definition of specified class definition.
Syntax:
ClassName ReferenceVariable =
(ClassName) Class.forName("PackageName.ClassName").newInstance();
Java
// Java program to demonstrate
// object creation using newInstance() method
// Base class
class Example {
void message()
{
System.out.println("Hello Geeks !!");
}
}
// Driver class
class Test {
public static void main(String args[])
{
try {
Class c = Class.forName("Example");
Example s = (Example)c.newInstance();
s.message();
}
catch (Exception e) {
System.out.println(e);
}
}
}
- Using newInstance() method for Constructor class: It is a reflective way to create object. By using it one can call parameterized and private constructor. It wraps the thrown exception with an InvocationTargetException. It is used by different frameworks- Spring, Hibernate, Struts etc. Constructor.newInstance() method is preferred over Class.newInstance() method.
Syntax:
Constructor constructor = ClassName.class.getConstructor();
ClassName ReferenceVariable = constructor.newInstance();
Example:
Java
// java program to demonstrate
// creation of object
// using Constructor.newInstance() method
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ConstructorExample {
// different exception is thrown
public static void main(String[] args)
throws NoSuchMethodException,
SecurityException,
InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
{
Constructor constructor = ExampleClass.class
.getConstructor(String.class);
ExampleClass exampleObject = (ExampleClass)constructor
.newInstance("GeeksForGeeks");
System.out.println(exampleObject.getemp_name());
}
}
class ExampleClass {
// private variable declared
private String emp_name;
public ExampleClass(String emp_name)
{
this.emp_name = emp_name;
}
// get method for emp_named to access
// private variable emp_name
public String getemp_name()
{
return emp_name;
}
// set method for emp_name to access
// private variable emp_name
public void setemp_name(String emp_name)
{
this.emp_name = emp_name;
}
}
- Using clone() method: It is used to make clone of an object. It is the easiest and most efficient way to copy an object. In code, java.lang.Cloneable interface must be implemented by the class whose object clone is to be created. If Cloneable interface is not implemented, clone() method generates CloneNotSupportedException .
Syntax:
ClassName ReferenceVariable = (ClassName) ReferenceVariable.clone();
Example:
Java
// java program to demonstrate
// object creation using clone() method
// employee class whose objects are cloned
class Employee implements Cloneable {
int emp_id;
String emp_name;
// default constructor
Employee(String emp_name, int emp_id)
{
this.emp_id = emp_id;
this.emp_name = emp_name;
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
// driver class
public class Test {
public static void main(String args[])
{
try {
Employee ob1 = new Employee("Tom", 201);
// Creating a new reference variable ob2
// which is pointing to the same address as ob1
Employee ob2 = (Employee)ob1.clone();
System.out.println(ob1.emp_id + ", " + ob1.emp_name);
System.out.println(ob2.emp_id + ", " + ob2.emp_name);
}
catch (CloneNotSupportedException c) {
System.out.println("Exception: " + c);
}
}
}
- Using deserialization: To deserialize an object, first implement a serializable interface in the class. No constructor is used to create an object in this method.
Syntax:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(FileName));
ClassName ReferenceVariable = (ClassName) in.readObject();
Example:
Java
// Java code to demonstrate object
// creation by deserialization
import java.io.*;
// Base class
class Example implements java.io.Serializable {
public int emp_id;
public String emp_name;
// Default constructor
public Example(int emp_id, String emp_name)
{
this.emp_id = emp_id;
this.emp_name = emp_name;
}
}
// Driver class
class Test {
public static void main(String[] args)
{
Example object = new Example(1, "geeksforgeeks");
String filename = "file1.ser";
// Serialization
try {
// Saving of object in a file
FileOutputStream file1 = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file1);
// Method for serialization of object
out.writeObject(object);
out.close();
file1.close();
System.out.println("Object has been serialized");
}
catch (IOException ex) {
System.out.println("IOException is caught");
}
Example object1 = null;
// Deserialization
try {
// Reading object from a file
FileInputStream file1 = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file1);
// Method for deserialization of object
object1 = (Example)in.readObject();
in.close();
file1.close();
System.out.println("Object has been deserialized");
System.out.println("Employee ID = " + object1.emp_id);
System.out.println("Employee Name = " + object1.emp_name);
}
catch (IOException ex) {
System.out.println("IOException is caught");
}
catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException is caught");
}
}
}
OutputObject has been serialized
Object has been deserialized
Employee ID = 1
Employee Name = geeksforgeeks
Differences between Objects and Classes

Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. Known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Syntax and s
10 min read
Basics
Introduction to JavaJava is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read
Java Programming BasicsJava is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming console
4 min read
Java MethodsJava Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects.Example: Java program to demonstrate how to crea
7 min read
Access Modifiers in JavaIn Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself, can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. In this article
6 min read
Arrays in JavaIn Java, an array is an important linear data structure that allows us to store multiple values of the same type. Arrays in Java are objects, like all other objects in Java, arrays implicitly inherit from the java.lang.Object class. This allows you to invoke methods defined in Object (such as toStri
9 min read
Java StringsIn Java, a String is the type of object that can store a sequence of characters enclosed by double quotes and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowin
8 min read
Regular Expressions in JavaIn Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressi
7 min read
OOPs & Interfaces
Classes and Objects in JavaIn 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
10 min read
Java ConstructorsIn Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automaticall
10 min read
Java OOP(Object Oriented Programming) ConceptsBefore Object-Oriented Programming (OOPs), most programs used a procedural approach, where the focus was on writing step-by-step functions. This made it harder to manage and reuse code in large applications.To overcome these limitations, Object-Oriented Programming was introduced. Java is built arou
10 min read
Java PackagesPackages in Java are a mechanism that encapsulates a group of classes, sub-packages and interfaces. Packages are used for: Prevent naming conflicts by allowing classes with the same name to exist in different packages, like college.staff.cse.Employee and college.staff.ee.Employee.They make it easier
8 min read
Java InterfaceAn Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
11 min read
Collections
Exception Handling
Java Exception HandlingException handling in Java is an effective mechanism for managing runtime errors to ensure the application's regular flow is maintained. Some Common examples of exceptions include ClassNotFoundException, IOException, SQLException, RemoteException, etc. By handling these exceptions, Java enables deve
8 min read
Java Try Catch BlockA try-catch block in Java is a mechanism to handle exceptions. This make sure that the application continues to run even if an error occurs. The code inside the try block is executed, and if any exception occurs, it is then caught by the catch block.Example: Here, we are going to handle the Arithmet
4 min read
Java final, finally and finalizeIn Java, the keywords "final", "finally" and "finalize" have distinct roles. final enforces immutability and prevents changes to variables, methods, or classes. finally ensures a block of code runs after a try-catch, regardless of exceptions. finalize is a method used for cleanup before an object is
4 min read
Chained Exceptions in JavaChained Exceptions in Java allow associating one exception with another, i.e. one exception describes the cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero.But the root cause of the error was an I/O f
3 min read
Null Pointer Exception in JavaA NullPointerException in Java is a RuntimeException. It occurs when a program attempts to use an object reference that has the null value. In Java, "null" is a special value that can be assigned to object references to indicate the absence of a value.Reasons for Null Pointer ExceptionA NullPointerE
5 min read
Exception Handling with Method Overriding in JavaException handling with method overriding in Java refers to the rules and behavior that apply when a subclass overrides a method from its superclass and both methods involve exceptions. It ensures that the overridden method in the subclass does not declare broader or new checked exceptions than thos
4 min read
Java Advanced
Java Multithreading TutorialThreads are the backbone of multithreading. We are living in the real world which in itself is caught on the web surrounded by lots of applications. With the advancement in technologies, we cannot achieve the speed required to run them simultaneously unless we introduce the concept of multi-tasking
15+ min read
Synchronization in JavaIn multithreading, synchronization is important to make sure multiple threads safely work on shared resources. Without synchronization, data can become inconsistent or corrupted if multiple threads access and modify shared variables at the same time. In Java, it is a mechanism that ensures that only
10 min read
File Handling in JavaIn Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used to create an object of the class and then specifying the name of the file.Why File Handling is Required?File Handling is an integral part of any programming languag
6 min read
Java Method ReferencesIn Java, a method is a collection of statements that perform some specific task and return the result to the caller. A method reference is the shorthand syntax for a lambda expression that contains just one method call. In general, one does not have to pass arguments to method references.Why Use Met
9 min read
Java 8 Stream TutorialJava 8 introduces Stream, which is a new abstract layer, and some new additional packages in Java 8 called java.util.stream. A Stream is a sequence of components that can be processed sequentially. These packages include classes, interfaces, and enum to allow functional-style operations on the eleme
15+ min read
Java NetworkingWhen computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is
15+ min read
JDBC TutorialJDBC stands for Java Database Connectivity. JDBC is a Java API or tool used in Java applications to interact with the database. It is a specification from Sun Microsystems that provides APIs for Java applications to communicate with different databases. Interfaces and Classes for JDBC API comes unde
12 min read
Java Memory ManagementJava memory management is the process by which the Java Virtual Machine (JVM) automatically handles the allocation and deallocation of memory. It uses a garbage collector to reclaim memory by removing unused objects, eliminating the need for manual memory managementJVM Memory StructureJVM defines va
4 min read
Garbage Collection in JavaGarbage collection in Java is an automatic memory management process that helps Java programs run efficiently. Java programs compile to bytecode that can be run on a Java Virtual Machine (JVM). When Java programs run on the JVM, objects in the heap are created, which is a portion of memory dedicated
7 min read
Memory Leaks in JavaIn programming, a memory leak happens when a program keeps using memory but does not give it back when it's done. It simply means the program slowly uses more and more memory, which can make things slow and even stop working. Working of Memory Management in JavaJava has automatic garbage collection,
3 min read
Practice Java
Java Interview Questions and AnswersJava is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java Programs - Java Programming ExamplesIn this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Exercises - Basic to Advanced Java Practice Programs with SolutionsLooking for Java exercises to test your Java skills, then explore our topic-wise Java practice exercises? Here you will get 25 plus practice problems that help to upscale your Java skills. As we know Java is one of the most popular languages because of its robust and secure nature. But, programmers
7 min read
Java Quiz | Level Up Your Java SkillsThe best way to scale up your coding skills is by practicing the exercise. And if you are a Java programmer looking to test your Java skills and knowledge? Then, this Java quiz is designed to challenge your understanding of Java programming concepts and assess your excellence in the language. In thi
1 min read
Top 50 Java Project Ideas For Beginners and Advanced [Update 2025]Java is one of the most popular and versatile programming languages, known for its reliability, security, and platform independence. Developed by James Gosling in 1982, Java is widely used across industries like big data, mobile development, finance, and e-commerce.Building Java projects is an excel
15+ min read