Here's a comprehensive 5-mark answer on Object-Oriented Programming (OOP):
Object-Oriented Programming (OOP)
Definition
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around data, or objects, rather than functions and logic. It focuses on creating reusable, modular code by representing real-world entities as objects with specific properties and behaviors.
Key Characteristics of OOP
1. Classes and Objects
- A class is a blueprint for creating objects, defining their properties (attributes) and behaviors (methods).
- An object is an instance of a class that represents a specific entity.
Example in Java:
public class Car {
// Attributes
String model;
int year;
// Method
public void drive() {
System.out.println("Car is moving");
}
}
// Creating an object
Car myCar = new Car();
2. Encapsulation
- Bundling data and methods that operate on that data within a single unit
- Restricting direct access to some of an object's components
- Achieved using access modifiers like private, protected, and public
Example:
public class BankAccount {
private double balance; // Private attribute
public void deposit(double amount) {
// Method controls how balance can be modified
balance += amount;
}
}
3. Inheritance
- Allows a class to inherit properties and methods from another class
- Promotes code reusability and establishes a hierarchical relationship between classes
Example:
public class Animal {
void eat() {
System.out.println("This animal eats");
}
}
public class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
4. Polymorphism
- Ability of objects to take on multiple forms
- Allows methods to do different things based on the object calling them
- Implemented through method overloading and method overriding
Example:
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
// Method overriding
void draw() {
System.out.println("Drawing a circle");
}
}
5. Abstraction
- Hiding complex implementation details
- Showing only the necessary features of an object
- Achieved through abstract classes and interfaces
Example:
abstract class Vehicle {
abstract void move(); // Abstract method
}
class Car extends Vehicle {
void move() {
System.out.println("Car is moving");
}
}
Conclusion
OOP provides a powerful approach to software design by creating modular, flexible, and maintainable code through its core principles of encapsulation, inheritance, polymorphism, and abstraction.