In Java, objects are the basic building blocks of object-oriented programming. Any entity in a Java program - from simple data structures to complex systems - is represented as an object. Knowing how objects are created, used, and destroyed forms the basis for writing efficient Java applications.
This blog will be covering the details of Java objects, the Object class, object creation, garbage collection, and memory management.
1. What is an Object in Java?
An object is an instance of a class that represents a real-world entity. It has:
- State (Attributes/Fields) – Data stored in variables
- Behavior (Methods) – Actions performed by the object
- Identity (Memory Address) – Unique identity in memory
Example of an Object
java
class Car {
String brand;
int speed;
void accelerate() {
System.out.println(brand + " is accelerating.");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Creating an object
myCar.brand = "Toyota";
myCar.speed = 120;
myCar.accelerate();
}
}
Output:
Toyota is accelerating.
Here, myCar
is an object of the Car
class.
2. How to Create Objects in Java?
Objects in Java can be created by using several methods:
1. Using the new
Keyword (Most Common Method)
java
Car myCar = new Car();
2. Using Reflection (Class.newInstance()
)
java
Car myCar = Car.class.newInstance(); // Requires exception handling
3. Using Clone Method (clone()
)
java
Car myCar2 = (Car) myCar.clone();
4. Using Deserialization
java
ObjectInputStream in = new ObjectInputStream(new FileInputStream("car.ser"));
Car myCar = (Car) in.readObject();
---
## **3. The Object Class in Java**
The `Object` class is the parent class of all Java classes. Every class in Java implicitly inherits from `Object`.
### **Methods of the `Object` Class**
| Method | Description |
|--------|-------------|
| `toString()` | Returns a string representation of the object |
| `equals(Object obj)` | Checks if two objects are equal |
| `hashCode()` | Returns the hash code of the object |
| `clone()` | Creates a duplicate of an object |
| `getClass()` | Returns the runtime class of an object |
| `finalize()` | Called before an object is garbage collected |
### **Example of Overriding `toString()`**
```java
class Car {
String brand;
Car(String brand) {
this.brand = brand;
}
@Override
public String toString() {
return "Car brand: " + brand;
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota");
System.out.println(myCar.toString());
}
}
Output:
Car brand: Toyota
4. Object Comparison in Java
Objects can be compared using:
1. ==
Operator (Compares Memory Address)
Car car1 = new Car("Toyota");
Car car2 = new Car("Toyota");
System.out.println(car1 == car2); // false (Different objects in memory)
2. equals()
Method (Compares Content, Needs Overriding)
@Override
public boolean equals(Object obj) {
if (obj instanceof Car) {
Car other = (Car) obj;
return this.brand.equals(other.brand);
}
return false;
}
-
5. Java Object Cloning
Object Cloning produces an object which is a replica of the existing one.
Through clone()
Method
java
class Car implements Cloneable {
String brand;
Car(String brand) {
this.brand = brand;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Car car1 = new Car(Toyota
);
Car car2 = (Car) car1.clone();
System.out.println(car1.brand); // Toyota
System.out.println(car2.brand); // Toyota
}
}
---
## **6. Object Destruction and Garbage Collection**
Java automatically manages memory using **garbage collection (GC)**. When an object is no longer needed, GC removes it from memory.
### **1. How Garbage Collection Works?**
- Objects with no references are **eligible for GC**.
- Java runs the garbage collector in the background.
- `System.gc()` can be used to **request** garbage collection (not guaranteed).
### **2. Finalize Method (`finalize()`)**
It can be seen that the `finalize()` method is called by the JVM before its object is destroyed.
java
class Car {
@Override
protected void finalize() {
System.out.println(Car object is being destroyed.
);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
``
myCar = null; // Eligible for GC
System.gc(); // Request GC
}
}
Output (May Vary):
Car object is being destroyed.
------
## **7. Memory Management for Objects**
### **1. Heap Memory and Stack Memory**
- Heap Memory: All objects created by `new`.
- **Stack Memory**: Stores method calls and primitive data types.
### **2. Strong vs. Weak References**
- **Strong Reference** – Prevents GC
- **Weak Reference** – Allows GC
java
WeakReferenceToyota
));
---
## **8. Best Practices for Object Creation and Management**
1. **Use constructors to initialize objects properly.**
2. **Override `equals()` and `hashCode()` methods when necessary.**
3. **Do not create unnecessary objects to save memory.**
4. **Use `WeakReference` for objects that can be garbage collected.**
5. **Manually close resources (`try-with-resources`).**
---
## **Conclusion**
Understanding Java's **objects and Object class** is essential for writing efficient and optimized programs.
- Objects represent real-world entities and are created using `new`.
- The **Object class** provides common methods like `toString()`, `equals()`, and `clone()`.
- Java provides **garbage collection** that automatically manages memory.
- Correct handling of objects enhances performance and reduces memory leaks.
Practice these concepts, and you will become a better Java developer to write **scalable and optimized** applications.