Object-Oriented Programming Concepts
1. Encapsulation
Encapsulation bundles data and methods into a single unit (class) and restricts direct access to internal details.
// Java Example: Encapsulation
class BankAccount {
private double balance; // hidden data
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if(amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient funds!");
}
}
public double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(500);
account.withdraw(200);
System.out.println("Balance: " + account.getBalance());
}
}
2. Inheritance
Inheritance allows a class to acquire properties and behaviors of another class.
// Java Example: Inheritance
class Vehicle {
int speed = 60;
void drive() {
System.out.println("Vehicle is driving at " + speed + " km/h");
}
}
class Car extends Vehicle {
void honk() {
System.out.println("Car is honking!");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.drive(); // inherited method
car.honk(); // child-specific method
}
}
3. Polymorphism
Polymorphism allows the same method to behave differently depending on the object.
// Java Example: Polymorphism
class Animal {
void makeSound() {
System.out.println("Some generic sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof Woof");
}
}
class Cat extends Animal {
void makeSound() {
System.out.println("Meow Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a1 = new Dog();
Animal a2 = new Cat();
a1.makeSound(); // Woof Woof
a2.makeSound(); // Meow Meow
}
}
4. Abstraction
Abstraction hides implementation details and exposes only essential features.
// Java Example: Abstraction
abstract class Vehicle {
abstract void start(); // abstract method
abstract void stop();
}
class Bike extends Vehicle {
void start() {
System.out.println("Bike started with a kick");
}
void stop() {
System.out.println("Bike stopped");
}
}
public class Main {
public static void main(String[] args) {
Vehicle v = new Bike();
v.start();
v.stop();
}
}