Difference between object and reference
In Java, an object and a reference are two related but distinct concepts:
Table of Contents
1. Object:
- An object is a runtime entity that represents an instance of a class.
- It occupies memory and has a state (defined by its fields) and behavior (defined by its methods).
- Objects are created using the `new` keyword followed by a constructor invocation.
2. Reference:
- A reference is a variable that holds the memory address (or reference) of an object.
- It does not actually contain the object itself, but rather a pointer to the object in memory.
- References allow us to access and manipulate objects indirectly.
Here’s a breakdown of the differences between objects and references:
- Existence: Objects exist at runtime and represent instances of classes, while references exist at compile-time and hold memory addresses of objects.
- Memory Usage: Objects occupy memory in the heap, whereas references typically occupy memory on the stack or in other parts of memory, depending on the context (local variables, fields, arrays, etc.).
- Creation: Objects are created using constructors with the `new` keyword, while references are created when variables are declared.
- Direct vs. Indirect Access: Objects can be accessed and manipulated directly using their methods and fields, while references are used to indirectly access objects.
- Relationship: An object can be referenced by multiple references, allowing for multiple access points to the same object.
- Lifetime: The lifetime of an object is determined by the garbage collector based on whether it is reachable or not. References can go out of scope or be reassigned, but the object they refer to may still exist if it is reachable.
Here’s a simple example to illustrate the difference:
Example
```java
public class ObjectReferenceExample {
public static void main(String[] args) {
// Creating an object of class MyClass
MyClass obj = new MyClass();
// 'obj' is a reference to the object
// 'obj' holds the memory address of the object in memory
}
}
class MyClass {
// Class definition
}
```
In this example, `obj` is a reference variable that holds the memory address of an object of type `MyClass`. The object itself exists in memory, while `obj` is just a reference to it.