Practical Coding Examples
Real-World Scenario: Shape Calculation
abstract class Shape {
public abstract double calculateArea();
public abstract double calculatePerimeter();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double calculateArea() {
return width * height;
}
@Override
public double calculatePerimeter() {
return 2 * (width + height);
}
}
Banking System Example
class BankAccount {
protected double balance;
public void deposit(double amount) {
balance += amount;
}
public virtual void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
}
}
}
class SavingsAccount extends BankAccount {
private double interestRate;
@Override
public void withdraw(double amount) {
if (balance - amount >= 100) {
super.withdraw(amount);
} else {
System.out.println("Minimum balance requirement not met");
}
}
public void applyInterest() {
balance += balance * interestRate;
}
}
Method Overriding Complexity Levels
graph TD
A[Method Overriding Complexity] --> B[Basic Overriding]
A --> C[Complex Overriding]
A --> D[Advanced Polymorphic Techniques]
Comparison of Overriding Techniques
Technique |
Complexity |
Use Case |
Simple Method Replacement |
Low |
Basic inheritance |
Conditional Overriding |
Medium |
Business logic implementation |
Super Method Invocation |
High |
Extended functionality |
Exception Handling in Overridden Methods
class NetworkService {
public void connect() throws IOException {
// Base connection method
}
}
class SecureNetworkService extends NetworkService {
@Override
public void connect() throws ConnectException {
// More specific exception handling
}
}
LabEx Learning Approach
In LabEx learning environments, method overriding is demonstrated through progressive complexity:
- Basic inheritance concepts
- Polymorphic behavior
- Advanced design patterns
Best Practices
- Always use
@Override
annotation
- Maintain liskov substitution principle
- Keep method contracts consistent
- Handle exceptions appropriately
Advanced Polymorphic Example
interface Playable {
void play();
void pause();
}
class AudioPlayer implements Playable {
@Override
public void play() {
System.out.println("Playing audio");
}
@Override
public void pause() {
System.out.println("Audio paused");
}
}
class VideoPlayer implements Playable {
@Override
public void play() {
System.out.println("Playing video");
}
@Override
public void pause() {
System.out.println("Video paused");
}
}