Data Analytics
# 📚 Java Programming Language – Part 5/10: Inheritance & Polymorphism #Java #OOP #Inheritance #Polymorphism #Programming Welcome to Part 5 of our Java series! Today we'll explore two fundamental OOP concepts: Inheritance and Polymorphism. --- ## 🔹 Inheritance…
## 🔹 Practical Example: Payment System
---
## 🔹 Marker Interfaces
Interfaces with no methods (used to mark classes).
---
## 🔹 Functional Interfaces (Java 8+)
Interfaces with exactly one abstract method (for lambdas).
---
## 🔹 Best Practices
1. Use interfaces for multiple inheritance needs
2. Use abstract classes for code reuse among related classes
3. Prefer interfaces for APIs
4. Use @Override annotation consistently
5. Follow interface segregation principle (small, focused interfaces)
---
### 📌 What's Next?
In Part 7, we'll cover:
➡️ Packages
➡️ Access Modifiers
➡️ Encapsulation Deep Dive
#JavaInterfaces #AbstractClasses #OOPConcepts 🚀
interface PaymentMethod {
void processPayment(double amount);
boolean validate();
}
abstract class OnlinePayment implements PaymentMethod {
protected String cardNumber;
public OnlinePayment(String cardNumber) {
this.cardNumber = cardNumber;
}
@Override
public boolean validate() {
return cardNumber != null && cardNumber.length() == 16;
}
}
class CreditCardPayment extends OnlinePayment {
public CreditCardPayment(String cardNumber) {
super(cardNumber);
}
@Override
public void processPayment(double amount) {
if (validate()) {
System.out.printf("Processing $%.2f via credit card %s\n",
amount, cardNumber.substring(12));
}
}
}
class PayPalPayment implements PaymentMethod {
private String email;
public PayPalPayment(String email) {
this.email = email;
}
@Override
public boolean validate() {
return email != null && email.contains("@");
}
@Override
public void processPayment(double amount) {
if (validate()) {
System.out.printf("Processing $%.2f via PayPal to %s\n",
amount, email);
}
}
}---
## 🔹 Marker Interfaces
Interfaces with no methods (used to mark classes).
interface Serializable { } // Example of marker interface
class MyClass implements Serializable {
// Class implementation
}---
## 🔹 Functional Interfaces (Java 8+)
Interfaces with exactly one abstract method (for lambdas).
@FunctionalInterface
interface Calculator {
int operate(int a, int b);
}
// Usage with lambda:
Calculator add = (a, b) -> a + b;
Calculator multiply = (a, b) -> a * b;
System.out.println(add.operate(5, 3)); // 8
System.out.println(multiply.operate(5, 3)); // 15
---
## 🔹 Best Practices
1. Use interfaces for multiple inheritance needs
2. Use abstract classes for code reuse among related classes
3. Prefer interfaces for APIs
4. Use @Override annotation consistently
5. Follow interface segregation principle (small, focused interfaces)
---
### 📌 What's Next?
In Part 7, we'll cover:
➡️ Packages
➡️ Access Modifiers
➡️ Encapsulation Deep Dive
#JavaInterfaces #AbstractClasses #OOPConcepts 🚀
❤3