Classes and Objects in Java
-
Last Updated: February 4, 2025
-
By: javahandson
-
Series
Learn everything about classes and objects in Java including the concepts of class definition, object creation, and their importance in Object-Oriented Programming (OOP). Explore memory allocation for objects, object lifecycle, and garbage collection in Java and understand the difference between class, object, and instance. This comprehensive guide will help you master the foundational concepts of Java programming for better performance and memory management.
A class in Java is a blueprint or a template for creating objects. It defines the state (fields/variables) and behavior (methods) that objects of that class will have.
class ClassName { // Instance variables (State) DataType variable1; DataType variable2; // Constructor (Optional) ClassName() { // Initialization code } // Methods (Behavior) void method1() { // Method logic } void method2() { // Method logic } }
Create a Student class template
class Student { // Instance variables (State) String name; int age; String grade; // Constructor to initialize student details Student(String studentName, int studentAge, String studentGrade) { name = studentName; age = studentAge; grade = studentGrade; } // Method to display student information void displayStudentInfo() { System.out.println("Student Name: " + name); System.out.println("Age: " + age); System.out.println("Grade: " + grade); } }
In this example, the Student class definition is as below:
An object is an instance of a class. It is a real-world entity that has a state (data) and behavior (methods). Objects are created from a class using the new keyword.
ClassName objectName = new ClassName();
or
ClassName objectName = new ClassName(parameters); // If the class has a constructor
Create a Student class object
public class Main { public static void main(String[] args) { // Creating an object of Student class with 3 variables Student student1 = new Student("Suraj", 35, "A"); // Calling method using the object student1.displayInfo(); } } Output: Student Name: Suraj Age: 35 Grade: A
Here, student1 is an object of class Student, and it has its own name, age, and grade values.
Class and object are the foundation of Object-Oriented Programming (OOP) in Java. Their importance includes:
Encapsulation – A class bundles data (variables) and methods together, protecting them from direct access.
Code Reusability – Once a class is defined, multiple objects can be created without rewriting the logic.
Modularity – Code is organized into reusable components, making it easier to maintain.
Abstraction – A class can hide implementation details and expose only necessary functionalities.
Polymorphism – Objects of different classes can behave differently while sharing the same method signature.
Inheritance – Classes can inherit properties and behaviors from other classes, promoting code reusability.
Example: Instead of defining data separately for each student, we use a Student class and create multiple student objects. This approach follows the DRY (Don’t Repeat Yourself) principle.
When an object is created in Java, memory is allocated in different areas of the JVM (Java Virtual Machine), primarily in the Heap, Stack, and Method Area (Class Memory).
a. Heap Memory (Object Storage)
b. Stack Memory (Method Execution)
c. Method Area (Class Memory)
This memory is shared among all objects of the class. Stores class-level data such as:
class Student { // Instance variables (stored in Heap Memory) String name; int age; // Static variable (stored in Method Area/Class Memory) static String school = "Mount Carmel Convent High School"; // Constructor Student(String name, int age) { this.name = name; this.age = age; } // Method to display student details void display() { System.out.println("Student Name: " + name); System.out.println("Age: " + age); System.out.println("School: " + school); // Accessing static variable } } public class Main { public static void main(String[] args) { // Stack memory: Stores reference variable (student1) // Heap memory: Stores object data (name = "Suraj", age = 34) Student student1 = new Student("Suraj", 34); Student student2 = new Student("Shweta", 32); student1.display(); student2.display(); } }
Heap Memory (Instance Variables & Objects)
Stack Memory (Local References)
Method Area (Class Memory)
In Java, the object lifecycle refers to the stages that an object goes through from its creation to its eventual destruction. Garbage Collection (GC) plays a crucial role in the management of memory, ensuring that objects no longer in use are removed from memory automatically.
The lifecycle of an object in Java involves the following stages:
a. Object Creation – An object is created when a class is instantiated using the new keyword. Memory is allocated in Heap memory for the object. The constructor of the class is called to initialize the object’s fields.
b. Object Initialization – After object creation, the constructor is executed to initialize the object’s state (instance variables). At this point, the object exists in memory, and you can call methods or access instance variables on it.
c. Object Usage – Once the object is initialized, it can be used throughout the program. Methods can be called, and data can be modified as long as the object has references pointing to it.
d. Object Dereferencing – When an object is no longer referenced (no variable points to it), it is said to be dereferenced. If there are no active references to the object, it becomes eligible for Garbage Collection.
e. Object Destruction – The Garbage Collector (GC) automatically reclaims the memory used by objects that are no longer in use. Once an object is collected by the GC, its memory is freed up, and the object is considered destroyed.
Garbage Collection is the process of automatically identifying and removing objects that are no longer referenced, thereby reclaiming memory. Java has an automatic garbage collection mechanism, which makes memory management easier by freeing memory used by objects that are no longer needed.
a. Reachability – An object is considered reachable if it is referenced directly or indirectly by any active thread. If no active thread or reference variable can access an object, it becomes unreachable and eligible for garbage collection.
b. Generational Garbage Collection – Java uses a generational garbage collection strategy, where objects are grouped into different generations based on their age:
c. Finalization -Java provides the finalize() method that is called by the garbage collector before an object is collected. However, relying on finalize() for resource cleanup is discouraged, as it may not be executed immediately.
d. GC Algorithms – Java uses various garbage collection algorithms, like Serial GC, Parallel GC, CMS (Concurrent Mark-Sweep), and G1 (Garbage First), to manage memory efficiently.
class Employee { String name; Employee(String name) { this.name = name; } // finalize method to observe garbage collection (not recommended to rely on this) @Override protected void finalize() throws Throwable { System.out.println("Finalizing " + name); super.finalize(); } } public class Main { public static void main(String[] args) { Employee emp1 = new Employee("Suraj"); Employee emp2 = new Employee("Shweta"); // Dereferencing emp1, it is now eligible for garbage collection emp1 = null; // Requesting garbage collection explicitly (though it's not recommended to call directly) System.gc(); // Suggests JVM to run garbage collection // Now emp2 is still reachable emp2 = null; // Request garbage collection again System.gc(); // Wait for garbage collection to happen try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } Output: Finalizing Suraj Finalizing Shweta
While you can request garbage collection using System.gc(), it is generally not recommended to force it. The JVM’s garbage collector is designed to run automatically when needed, and forcing it may not result in an immediate collection of objects.
Class – A class is a blueprint or template for creating objects. It defines the structure (fields/variables) and behavior (methods) that objects of that class will have. A class itself does not contain any data; it simply defines the properties and actions of objects.
class Car { String model; int speed; void displayDetails() { System.out.println("Car Model: " + model); System.out.println("Car Speed: " + speed); } }
Here, Car is a class. It defines model and speed as attributes and a displayDetails() method.
Object – An object is an instance of a class. It is a real-world entity that holds the state defined by the class. When a class is instantiated, it creates an object, and memory is allocated in Heap memory for that object. An object can access the methods and attributes of its class.
public class Main { public static void main(String[] args) { Car myCar = new Car(); // Creating an object (instance) of Car class myCar.model = "Tesla"; myCar.speed = 120; myCar.displayDetails(); // Calling method on the object } }
Here, myCar is an object of the Car class. The myCar object holds the specific values for model and speed and has the displayDetails() method available to it.
Instance – An instance refers to a specific object created from a class. The term “instance” is often used to emphasize that a particular object is a unique occurrence of the class. Every object is an instance of a class, but an instance may be used when referring to a specific object or a particular occurrence of that class.
Car car1 = new Car(); // car1 is an instance of the Car class
Car car2 = new Car(); // car2 is another instance of the Car class
In Java, classes and objects are foundational concepts in Object-Oriented Programming (OOP). A class serves as a blueprint for creating objects, which are instances of that class, each holding its own state and behavior. Understanding the importance of classes and objects is essential for writing modular, reusable, and maintainable code.
The memory allocation for objects, primarily in Heap memory, and the object lifecycle, which includes creation, usage, and garbage collection, plays a crucial role in efficient memory management. The Garbage Collector automatically removes unreachable objects, ensuring optimal performance. Understanding the difference between class, object, and instance is key to avoiding confusion in object-oriented design.
By mastering these concepts, Java developers can build scalable applications with better memory handling and enhanced performance. Whether you are learning the basics or optimizing complex systems, the knowledge of classes and objects is crucial for becoming a proficient Java developer.
So this is all about classes and objects in Java. If you have any questions on this topic, please raise them in the comments section. If you liked this article then please share this post with your friends and colleagues.