In Java, an object is a fundamental unit of object-oriented programming (OOP) that represents a real-world entity.
Objects are instances of classes and are created using the new keyword followed by a constructor call.
Here's an overview of objects in Java:
A class is a blueprint or template for creating objects.
It defines the attributes (data) and methods (behaviour) that objects of that class will have.
public class Vehicle { // Attributes (data) String manufacturer; String model; int year; // Methods (behaviour) public void brake() { // Code to brake the vehicle } // Methods (behaviour) public void start() { // Code to start the vehicle } public void accelerate() { // Code to accelerate the vehicle } }
An object is created using the "new" keyword followed by a constructor call.
Vehicle yourVehicle = new Vehicle(); // Creating an object of the Vehicle class
The constructor initializes the object and allocates memory for it.
yourVehicle.manufacturer = "Volvo"; // Setting the manufacturer attribute yourVehicle.model = "2020-GLS"; // Setting the model attribute yourVehicle.year = 2020; // Setting the year attribute yourVehicle.start(); // Calling the start() method yourVehicle.brake(); // Calling the brake() method yourVehicle.accelerate(); // Calling the accelerate() method
Once an object is created, its members (attributes and methods) can be accessed using the dot "." operator.
Vehicle yourVehicle1 = new Vehicle(); // Creating object 1 Vehicle yourVehicle2 = yourVehicle1; // Creating object reference variable pointing to object 1
An object reference variable holds the memory address of the object rather than the object itself.
Multiple object reference variables can refer to the same object.
In Java, objects are dynamically allocated to the heap memory. When an object is no longer referenced by any variable, it becomes eligible for garbage collection.
The Java Virtual Machine (JVM) automatically reclaims the memory occupied by unreferenced objects through the process of garbage collection.
Objects play a central role in Java programming, allowing us to model real-world entities, encapsulate data and behaviour, and build complex systems with reusable components.
Understanding how to create and manipulate objects is essential for writing object-oriented Java programs.