Object-Oriented Programming in Java with Real-Life Examples
Object-Oriented Programming (OOP) in Java
Object-Oriented Programming (OOP) is a programming approach that organizes software design around objects rather than functions or logic. Java is a pure object-oriented programming language, which means everything revolves around objects and classes.
1. What Is an Object?
An object is a real-world entity that has:
- State (properties or characteristics)
- Behavior (actions or functionality) In Java:
- State is represented by instance variables
- Behavior is represented by instance methods
Java also supports a special member called an instance initializer block, which is used to initialize instance-level data.
This block executes when an object is created and does not initialize static members of the class.
Real-Life Example of an Object
Car Object
- State (Properties): color, speed, brand, fuelType
- Behavior (Functions): start(), accelerate(), brake(), stop()
Car
├─ State → color, speed, brand
└─ Behavior → start(), drive(), stop()
Just like a real car has features and actions, a Java object contains variables and methods.
2. Object Creation in Java
An object in Java is created using the new keyword along with a constructor.
🔹 Syntax
ClassName referenceVariable = new Constructor();
Explanation of Each Part
- ClassName
Represents the blueprint of the object.
Reference Variable
Stores the memory address of the object created in memory.
- new Keyword
Allocates memory dynamically and generates a unique hexadecimal memory address.
- Constructor
Initializes the object by placing data into the allocated memory.
Real-Life Example of Object Creation
Student Registration
- A student form (class) is filled
- A new student record (object) is created
- The record is stored in memory and accessed using a reference number
Student s1 = new Student();
Here:
- Student → blueprint
- s1 → reference variable
- new → creates memory
- Student() → initializes student data
Key Points to Remember
- Objects are created at runtime
- Reference variables store memory addresses, not actual objects
- Multiple objects can be created from the same class
- Each object has its own state
Comments
Post a Comment