Objects in Java
Definition
In Java, an object is a fundamental building block of Object-Oriented Programming (OOP) that represents a real-world entity. It is an "instance" of a class, containing both state (data stored in fields) and behavior (code defined in methods). While a class acts as a blueprint, the object is the actual entity that consumes memory and performs tasks during program execution.
Main Content
1. State and Behavior
- State: Represented by the attributes or fields (variables) of an object. For example, if you have a
Carobject, its state might include its color, model, and current speed. - Behavior: Represented by methods. This defines what the object can do, such as
accelerate(),brake(), orturn().
2. Identity and Reference
- Identity: Every object has a unique identity, usually implemented as a memory address in the Java Virtual Machine (JVM). Even if two objects have the same data, they are distinct entities.
- Reference: Java uses reference variables to manipulate objects. The variable holds the memory address where the object resides in the heap memory.
3. Object Creation
- An object is created using the
newkeyword. Whennewis called, it allocates memory on the heap, calls the constructor to initialize the object, and returns a reference to that memory space.
[ Blueprint/Class ] ----new----> [ Object in Heap ]
| - Data | | - Data: Red |
| - Methods | | - Method: Drive|
+-----------------+ +----------------+
Working / Process
1. Declaration
- You declare a reference variable of the class type, which currently points to
nullbecause no object has been created yet. - Example:
Car myCar;
2. Instantiation
- You use the
newkeyword to allocate memory for the object. Thenewkeyword triggers the JVM to reserve space in the heap. - Example:
myCar = new Car();
3. Initialization
- The constructor is called during instantiation. It sets the initial state of the object, ensuring that the fields have valid starting values.
- Example:
public Car() { speed = 0; }
Advantages / Applications
- Modularity: Objects allow code to be broken into manageable pieces, making it easier to maintain and troubleshoot.
- Encapsulation: Objects hide their internal data from the outside world, exposing only necessary methods, which increases security and reduces errors.
- Reusability: Once a class is defined, you can create as many objects as needed, promoting code reuse across different parts of an application.
Summary
An object is a specific instance of a class that combines data fields and methods into a single unit. It represents real-world entities in code, allowing developers to manage state and behavior efficiently. By using the new keyword, objects are allocated in heap memory, providing a modular and scalable approach to software development. Important terms to remember: Class, Instance, Heap Memory, Constructor, and Reference.