Basic OOP Concepts
The main Object-Oriented Programming (OOP) concepts are:
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
1. Inheritance
Inheritance is a concept where one class can acquire the properties and behaviors of another class. It helps reuse code and establish a relationship between classes.
In Java, there are two types of classes involved in inheritance:
- Parent class (also called Superclass or Base class) – the class whose properties are inherited.
- Child class (also called Subclass or Derived class) – the class that inherits properties from the parent.
๐Read more about Inheritance here.
Example :
2. Polymorphism :
Polymorphism means “many forms.” It is the ability of a variable, method, or object to take on multiple forms.
In Java, polymorphism is of two types:
- Compile-time polymorphism – achieved through method overloading.
- Run-time polymorphism – achieved through method overriding.
Example ;
3. Encapsulation :
Encapsulation is the process of wrapping data and methods together as a single unit. It also involves hiding data to prevent unauthorized access or modification.
In Java, encapsulation is achieved by:
- Declaring variables as private.
- Providing public getter and setter methods to access and modify these variables
Example:
class Person {
private String name; // private variable
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
4. Abstraction :
Abstraction is the process of hiding implementation details and showing only the functionality.
In Java, abstraction is achieved using:
- Interface – provides 100% abstraction (all methods are abstract).
- Abstract class – provides 0–100% abstraction (can have both abstract and concrete methods).
Example ;
abstract class Vehicle {
abstract void start(); // abstract method
}
interface Drivable {
void drive(); // abstract method
}