Object-Oriented Programming (OOP)
Let’s start from the beginning of Object-Oriented Programming (OOP) in Java, including examples of code to help illustrate the concepts. We’ll cover the core concepts like objects, classes, inheritance, encapsulation, polymorphism, and abstraction using code examples for clarity.
What is Object-Oriented Programming (OOP)?
OOP is a programming model where software design revolves around objects that represent real-world entities. Each object contains attributes (data) and methods (functions) that define its behavior. Instead of just focusing on procedures or functions, OOP models things based on objects and how they interact.
Example of an Object:
Consider a Car object in a real-world system:
- Attributes (data): Color, model, speed, year of manufacture.
- Methods (behavior): Start, stop, accelerate, brake.
In Java, we can model this as follows:
Example: Creating a Class and Objects
javaCopy code// Define a class (blueprint) for Car
class Car {
// Attributes of the car (fields)
String color;
String model;
int year;
int speed;
// Constructor to initialize the car
Car(String color, String model, int year, int speed) {
this.color = color;
this.model = model;
this.year = year;
this.speed = speed;
}
// Methods of the car (behavior)
void start() {
System.out.println(model + " has started.");
}
void accelerate(int increaseSpeed) {
speed += increaseSpeed;
System.out.println(model + " is accelerating. Speed is now: " + speed);
}
void stop() {
System.out.println(model + " has stopped.");
speed = 0;
}
}
public class Main {
public static void main(String[] args) {
// Create an object of the Car class
Car myCar = new Car("Red", "Toyota", 2022, 0);
// Using the methods of the Car object
myCar.start();
myCar.accelerate(50); // Accelerate by 50 units
myCar.stop();
}
}
Explanation:
- Class:
Car
is a blueprint or template that defines what a car is (its attributes) and what it can do (its methods). - Object:
myCar
is an instance of theCar
class with specific values for its attributes (red, Toyota, 2022). - Constructor:
Car()
initializes the object with data likecolor
,model
,year
, andspeed
. - Methods:
start()
,accelerate()
, andstop()
define the behaviors or actions that a car can perform.
Core Concepts of OOP
1. Encapsulation:
Encapsulation is about bundling the data (attributes) and methods (behaviors) together into a single unit (the object). It also controls the access to this data through access modifiers like private
, protected
, or public
.
javaCopy codeclass Car {
// Encapsulation: Fields are private to protect the data
private String color;
private String model;
private int year;
private int speed;
// Public getter and setter methods to access private fields
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public void start() {
System.out.println(model + " has started.");
}
}
Here, we encapsulate the data by declaring it private and only allow controlled access through public methods (getters and setters). This helps protect the internal state of the object.
2. Inheritance:
Inheritance allows one class to inherit the attributes and methods from another class. It helps in code reuse.
javaCopy code// Base class (Parent)
class Vehicle {
int speed;
void stop() {
System.out.println("The vehicle has stopped.");
}
}
// Derived class (Child) inherits from Vehicle
class Car extends Vehicle {
String model;
// Additional method in Car
void start() {
System.out.println(model + " has started.");
}
}
public class Main {
public static void main(String[] args) {
// Create a Car object which inherits from Vehicle
Car myCar = new Car();
myCar.model = "Honda";
myCar.start(); // Calls start() from Car
myCar.stop(); // Calls stop() from Vehicle (inherited method)
}
}
- Inheritance: The
Car
class inherits from theVehicle
class, reusing itsstop()
method and adding its ownstart()
method.
3. Polymorphism:
Polymorphism allows methods to behave differently based on the object calling them. There are two types:
- Method Overloading: Same method name with different parameters.
- Method Overriding: A method in the child class overrides the method in the parent class.
javaCopy code// Base class
class Vehicle {
void start() {
System.out.println("Vehicle is starting.");
}
}
// Derived class overrides the start() method
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car is starting.");
}
}
public class Main {
public static void main(String[] args) {
Vehicle myVehicle = new Vehicle();
Car myCar = new Car();
// Calls the start() method of Vehicle
myVehicle.start(); // Output: Vehicle is starting.
// Calls the overridden start() method of Car
myCar.start(); // Output: Car is starting.
}
}
- Overriding: The
Car
class overrides thestart()
method from theVehicle
class. Based on the object type, the correct method is called.
4. Abstraction:
Abstraction hides complex details and shows only the essential features. It can be implemented using abstract classes or interfaces.
javaCopy code// Abstract class
abstract class Vehicle {
// Abstract method (no body)
abstract void start();
// Regular method
void stop() {
System.out.println("Vehicle stopped.");
}
}
// Derived class implementing the abstract method
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car is starting.");
}
}
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car(); // Create an object of the derived class
myCar.start(); // Calls the Car's start() method
myCar.stop(); // Calls the stop() method from Vehicle class
}
}
- Abstract Class:
Vehicle
has an abstract methodstart()
that is implemented by theCar
class. This ensures that every subclass ofVehicle
will provide its own version ofstart()
.
OOP Advantages:
- Code Reusability: With inheritance, classes can reuse code, reducing duplication.
- Data Security: Encapsulation protects the object’s data from unintended modifications.
- Flexibility: Polymorphism allows the same code to work with different object types, making programs flexible and extensible.
- Abstraction: Hides complexity and allows focusing on the relevant details of a problem.
Summary:
- OOP helps organize complex software by modeling real-world entities as objects with attributes (data) and methods (behavior).
- Encapsulation protects the internal state, inheritance promotes code reuse, polymorphism allows flexibility, and abstraction hides complexity.