Introduction
Imagine you have a universal remote control that can operate different devices—TV, stereo, DVD player—each responding differently to the same "power" button. That's polymorphism in Java! It allows objects of different types to be treated as objects of a common supertype, with each executing their own specific behavior.
Polymorphism is like having multiple forms—the same action can behave differently depending on the actual object type, enabling flexible and extensible code design.
What is Polymorphism?
Polymorphism (from Greek "poly" meaning many, "morph" meaning forms) is the ability of an object to take on many forms. In Java, it allows methods to do different things based on the actual object being operated upon.
Key Characteristics:
- 🔄 Multiple forms: Same interface, different implementations
- 🎯 Runtime binding: Method resolution at execution time
- 📈 IS-A relationship: Based on inheritance and interfaces
- ⚡ Flexible design: Code works with general types
- 🚀 Extensibility: Easy to add new types
Code Explanation with Examples
Example 1: Basic Polymorphism with Inheritance
public class BasicPolymorphism {
public static void main(String[] args) {
System.out.println("=== BASIC POLYMORPHISM WITH INHERITANCE ===");
// Creating objects of different types
Animal genericAnimal = new Animal();
Animal myDog = new Dog(); // Polymorphism - Dog treated as Animal
Animal myCat = new Cat(); // Polymorphism - Cat treated as Animal
Animal myBird = new Bird(); // Polymorphism - Bird treated as Animal
// Same method call, different behaviors
System.out.println("Generic Animal: " + genericAnimal.makeSound());
System.out.println("Dog as Animal: " + myDog.makeSound());
System.out.println("Cat as Animal: " + myCat.makeSound());
System.out.println("Bird as Animal: " + myBird.makeSound());
// Polymorphism in arrays
System.out.println("\n=== POLYMORPHISM IN ARRAYS ===");
Animal[] animals = { genericAnimal, myDog, myCat, myBird };
for (Animal animal : animals) {
System.out.println(animal.getClass().getSimpleName() + " says: " + animal.makeSound());
}
// Method parameters polymorphism
System.out.println("\n=== METHOD PARAMETERS POLYMORPHISM ===");
AnimalHelper helper = new AnimalHelper();
helper.describeAnimal(genericAnimal);
helper.describeAnimal(myDog);
helper.describeAnimal(myCat);
helper.describeAnimal(myBird);
// Return type polymorphism
System.out.println("\n=== RETURN TYPE POLYMORPHISM ===");
AnimalFactory factory = new AnimalFactory();
Animal animal1 = factory.createAnimal("dog");
Animal animal2 = factory.createAnimal("cat");
Animal animal3 = factory.createAnimal("bird");
System.out.println("Created: " + animal1.getClass().getSimpleName() + " - " + animal1.makeSound());
System.out.println("Created: " + animal2.getClass().getSimpleName() + " - " + animal2.makeSound());
System.out.println("Created: " + animal3.getClass().getSimpleName() + " - " + animal3.makeSound());
}
}
class Animal {
public String makeSound() {
return "Some generic animal sound";
}
public String move() {
return "Animal is moving";
}
}
class Dog extends Animal {
@Override
public String makeSound() {
return "Woof! Woof!";
}
@Override
public String move() {
return "Dog is running happily";
}
// Dog-specific method
public void fetch() {
System.out.println("Dog is fetching the ball!");
}
}
class Cat extends Animal {
@Override
public String makeSound() {
return "Meow! Meow!";
}
@Override
public String move() {
return "Cat is moving gracefully";
}
// Cat-specific method
public void climb() {
System.out.println("Cat is climbing the tree!");
}
}
class Bird extends Animal {
@Override
public String makeSound() {
return "Chirp! Chirp!";
}
@Override
public String move() {
return "Bird is flying in the sky";
}
// Bird-specific method
public void fly() {
System.out.println("Bird is flying high!");
}
}
class AnimalHelper {
// Method accepts any Animal (polymorphic parameter)
public void describeAnimal(Animal animal) {
System.out.println("=== " + animal.getClass().getSimpleName() + " ===");
System.out.println("Sound: " + animal.makeSound());
System.out.println("Movement: " + animal.move());
// Type checking and casting for specific behaviors
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.fetch();
} else if (animal instanceof Cat) {
Cat cat = (Cat) animal;
cat.climb();
} else if (animal instanceof Bird) {
Bird bird = (Bird) animal;
bird.fly();
}
System.out.println();
}
}
class AnimalFactory {
// Polymorphic return type - returns different Animal subtypes
public Animal createAnimal(String type) {
return switch (type.toLowerCase()) {
case "dog" -> new Dog();
case "cat" -> new Cat();
case "bird" -> new Bird();
default -> new Animal();
};
}
}
Output:
=== BASIC POLYMORPHISM WITH INHERITANCE === Generic Animal: Some generic animal sound Dog as Animal: Woof! Woof! Cat as Animal: Meow! Meow! Bird as Animal: Chirp! Chirp! === POLYMORPHISM IN ARRAYS === Animal says: Some generic animal sound Dog says: Woof! Woof! Cat says: Meow! Meow! Bird says: Chirp! Chirp! === METHOD PARAMETERS POLYMORPHISM === === Animal === Sound: Some generic animal sound Movement: Animal is moving === Dog === Sound: Woof! Woof! Movement: Dog is running happily Dog is fetching the ball! === Cat === Sound: Meow! Meow! Movement: Cat is moving gracefully Cat is climbing the tree! === Bird === Sound: Chirp! Chirp! Movement: Bird is flying in the sky Bird is flying high! === RETURN TYPE POLYMORPHISM === Created: Dog - Woof! Woof! Created: Cat - Meow! Meow! Created: Bird - Chirp! Chirp!
Example 2: Polymorphism with Interfaces
public class InterfacePolymorphism {
public static void main(String[] args) {
System.out.println("=== POLYMORPHISM WITH INTERFACES ===");
// Different payment processors implementing same interface
PaymentProcessor creditCard = new CreditCardProcessor();
PaymentProcessor paypal = new PayPalProcessor();
PaymentProcessor crypto = new CryptoProcessor();
// Polymorphic payment processing
processPayment(creditCard, 100.0);
processPayment(paypal, 150.0);
processPayment(crypto, 200.0);
// Notification system polymorphism
System.out.println("\n=== NOTIFICATION SYSTEM ===");
Notification email = new EmailNotification();
Notification sms = new SMSNotification();
Notification push = new PushNotification();
sendNotification(email, "Welcome to our service!");
sendNotification(sms, "Your verification code: 123456");
sendNotification(push, "New message received!");
// Shape drawing polymorphism
System.out.println("\n=== SHAPE DRAWING ===");
Drawable[] shapes = {
new Circle(5.0),
new Rectangle(4.0, 6.0),
new Triangle(3.0, 4.0, 5.0)
};
drawAllShapes(shapes);
// Calculator polymorphism
System.out.println("\n=== CALCULATOR POLYMORPHISM ===");
Calculator basic = new BasicCalculator();
Calculator scientific = new ScientificCalculator();
Calculator programmer = new ProgrammerCalculator();
performCalculations(basic);
performCalculations(scientific);
performCalculations(programmer);
}
// Polymorphic method - works with any PaymentProcessor
public static void processPayment(PaymentProcessor processor, double amount) {
System.out.println("\nProcessing $" + amount + " payment...");
processor.authenticate();
processor.processPayment(amount);
System.out.println("Payment completed!");
}
// Polymorphic method - works with any Notification
public static void sendNotification(Notification notification, String message) {
notification.send(message);
System.out.println("Notification sent via: " + notification.getType());
}
// Polymorphic method - works with any Drawable
public static void drawAllShapes(Drawable[] shapes) {
for (Drawable shape : shapes) {
shape.draw();
System.out.println("Area: " + shape.calculateArea());
System.out.println("Perimeter: " + shape.calculatePerimeter());
System.out.println();
}
}
// Polymorphic method - works with any Calculator
public static void performCalculations(Calculator calculator) {
System.out.println("=== " + calculator.getClass().getSimpleName() + " ===");
System.out.println("10 + 5 = " + calculator.add(10, 5));
System.out.println("10 - 5 = " + calculator.subtract(10, 5));
System.out.println("10 * 5 = " + calculator.multiply(10, 5));
System.out.println("10 / 5 = " + calculator.divide(10, 5));
calculator.showCapabilities();
System.out.println();
}
}
// Payment processing interface
interface PaymentProcessor {
void authenticate();
void processPayment(double amount);
void refundPayment(String transactionId);
default String getProcessorName() {
return this.getClass().getSimpleName();
}
}
class CreditCardProcessor implements PaymentProcessor {
@Override
public void authenticate() {
System.out.println("Authenticating credit card...");
System.out.println("Card validated successfully");
}
@Override
public void processPayment(double amount) {
System.out.println("Processing credit card payment of $" + amount);
System.out.println("Charging card... Transaction approved!");
}
@Override
public void refundPayment(String transactionId) {
System.out.println("Processing refund for transaction: " + transactionId);
}
}
class PayPalProcessor implements PaymentProcessor {
@Override
public void authenticate() {
System.out.println("Authenticating with PayPal...");
System.out.println("PayPal account verified");
}
@Override
public void processPayment(double amount) {
System.out.println("Processing PayPal payment of $" + amount);
System.out.println("Redirecting to PayPal... Payment authorized!");
}
@Override
public void refundPayment(String transactionId) {
System.out.println("Processing PayPal refund for: " + transactionId);
}
}
class CryptoProcessor implements PaymentProcessor {
@Override
public void authenticate() {
System.out.println("Authenticating cryptocurrency wallet...");
System.out.println("Wallet address verified");
}
@Override
public void processPayment(double amount) {
System.out.println("Processing cryptocurrency payment of $" + amount);
System.out.println("Converting to BTC... Blockchain transaction confirmed!");
}
@Override
public void refundPayment(String transactionId) {
System.out.println("Processing crypto refund for: " + transactionId);
}
}
// Notification interface
interface Notification {
void send(String message);
String getType();
}
class EmailNotification implements Notification {
@Override
public void send(String message) {
System.out.println("Sending email: " + message);
}
@Override
public String getType() {
return "Email";
}
}
class SMSNotification implements Notification {
@Override
public void send(String message) {
System.out.println("Sending SMS: " + message);
}
@Override
public String getType() {
return "SMS";
}
}
class PushNotification implements Notification {
@Override
public void send(String message) {
System.out.println("Sending push notification: " + message);
}
@Override
public String getType() {
return "Push Notification";
}
}
// Drawable interface for shapes
interface Drawable {
void draw();
double calculateArea();
double calculatePerimeter();
}
class Circle implements Drawable {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing Circle with radius: " + radius);
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
class Rectangle implements Drawable {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public void draw() {
System.out.println("Drawing Rectangle: " + width + " x " + height);
}
@Override
public double calculateArea() {
return width * height;
}
@Override
public double calculatePerimeter() {
return 2 * (width + height);
}
}
class Triangle implements Drawable {
private double side1, side2, side3;
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
@Override
public void draw() {
System.out.println("Drawing Triangle with sides: " + side1 + ", " + side2 + ", " + side3);
}
@Override
public double calculateArea() {
// Heron's formula
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
@Override
public double calculatePerimeter() {
return side1 + side2 + side3;
}
}
// Calculator interface
interface Calculator {
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
void showCapabilities();
}
class BasicCalculator implements Calculator {
@Override
public double add(double a, double b) {
return a + b;
}
@Override
public double subtract(double a, double b) {
return a - b;
}
@Override
public double multiply(double a, double b) {
return a * b;
}
@Override
public double divide(double a, double b) {
if (b == 0) throw new ArithmeticException("Division by zero");
return a / b;
}
@Override
public void showCapabilities() {
System.out.println("Basic arithmetic operations");
}
}
class ScientificCalculator implements Calculator {
@Override
public double add(double a, double b) {
return a + b;
}
@Override
public double subtract(double a, double b) {
return a - b;
}
@Override
public double multiply(double a, double b) {
return a * b;
}
@Override
public double divide(double a, double b) {
if (b == 0) throw new ArithmeticException("Division by zero");
return a / b;
}
@Override
public void showCapabilities() {
System.out.println("Scientific functions: sin, cos, tan, log, etc.");
}
// Additional scientific methods
public double power(double base, double exponent) {
return Math.pow(base, exponent);
}
public double squareRoot(double number) {
return Math.sqrt(number);
}
}
class ProgrammerCalculator implements Calculator {
@Override
public double add(double a, double b) {
return a + b;
}
@Override
public double subtract(double a, double b) {
return a - b;
}
@Override
public double multiply(double a, double b) {
return a * b;
}
@Override
public double divide(double a, double b) {
if (b == 0) throw new ArithmeticException("Division by zero");
return a / b;
}
@Override
public void showCapabilities() {
System.out.println("Programmer functions: binary, hex, octal, bit operations");
}
// Additional programmer methods
public String toBinary(int number) {
return Integer.toBinaryString(number);
}
public String toHex(int number) {
return Integer.toHexString(number);
}
}
Output:
=== POLYMORPHISM WITH INTERFACES === Processing $100.0 payment... Authenticating credit card... Card validated successfully Processing credit card payment of $100.0 Charging card... Transaction approved! Payment completed! Processing $150.0 payment... Authenticating with PayPal... PayPal account verified Processing PayPal payment of $150.0 Redirecting to PayPal... Payment authorized! Payment completed! Processing $200.0 payment... Authenticating cryptocurrency wallet... Wallet address verified Processing cryptocurrency payment of $200.0 Converting to BTC... Blockchain transaction confirmed! Payment completed! === NOTIFICATION SYSTEM === Sending email: Welcome to our service! Notification sent via: Email Sending SMS: Your verification code: 123456 Notification sent via: SMS Sending push notification: New message received! Notification sent via: Push Notification === SHAPE DRAWING === Drawing Circle with radius: 5.0 Area: 78.53981633974483 Perimeter: 31.41592653589793 Drawing Rectangle: 4.0 x 6.0 Area: 24.0 Perimeter: 20.0 Drawing Triangle with sides: 3.0, 4.0, 5.0 Area: 6.0 Perimeter: 12.0 === CALCULATOR POLYMORPHISM === === BasicCalculator === 10 + 5 = 15.0 10 - 5 = 5.0 10 * 5 = 50.0 10 / 5 = 2.0 Basic arithmetic operations === ScientificCalculator === 10 + 5 = 15.0 10 - 5 = 5.0 10 * 5 = 50.0 10 / 5 = 2.0 Scientific functions: sin, cos, tan, log, etc. === ProgrammerCalculator === 10 + 5 = 15.0 10 - 5 = 5.0 10 * 5 = 50.0 10 / 5 = 2.0 Programmer functions: binary, hex, octal, bit operations
Example 3: Real-World Polymorphism Applications
import java.util.*;
public class RealWorldPolymorphism {
public static void main(String[] args) {
System.out.println("=== REAL-WORLD POLYMORPHISM APPLICATIONS ===");
// Employee management system
System.out.println("=== EMPLOYEE MANAGEMENT SYSTEM ===");
EmployeeManager manager = new EmployeeManager();
Employee fullTime = new FullTimeEmployee("Alice", 50000, 5000);
Employee partTime = new PartTimeEmployee("Bob", 25, 160);
Employee contractor = new Contractor("Charlie", 75, 200);
manager.addEmployee(fullTime);
manager.addEmployee(partTime);
manager.addEmployee(contractor);
manager.processPayroll();
manager.generateReports();
// E-commerce payment system
System.out.println("\n=== E-COMMERCE PAYMENT SYSTEM ===");
ShoppingCart cart = new ShoppingCart();
cart.addItem(new Product("Laptop", 999.99));
cart.addItem(new Product("Mouse", 29.99));
cart.addItem(new Product("Keyboard", 79.99));
// Polymorphic payment processing
cart.checkout(new CreditCardPayment());
cart.checkout(new PayPalPayment());
cart.checkout(new CryptoPayment());
// Vehicle rental system
System.out.println("\n=== VEHICLE RENTAL SYSTEM ===");
RentalService rental = new RentalService();
Vehicle car = new Car("Toyota Camry", 2023, 5);
Vehicle bike = new Motorcycle("Harley Davidson", 2022, 1200);
Vehicle truck = new Truck("Ford F-150", 2023, 2000);
rental.rentVehicle(car, 3);
rental.rentVehicle(bike, 2);
rental.rentVehicle(truck, 5);
rental.displayRentalSummary();
// Database operations
System.out.println("\n=== DATABASE OPERATIONS ===");
DatabaseManager dbManager = new DatabaseManager();
Database mysql = new MySQLDatabase();
Database postgres = new PostgreSQLDatabase();
Database mongodb = new MongoDB();
dbManager.performDatabaseOperations(mysql);
dbManager.performDatabaseOperations(postgres);
dbManager.performDatabaseOperations(mongodb);
}
}
// Employee Management System
abstract class Employee {
protected String name;
protected String employeeId;
public Employee(String name) {
this.name = name;
this.employeeId = generateEmployeeId();
}
// Abstract methods - polymorphic behavior
public abstract double calculateSalary();
public abstract double calculateBonus();
public abstract String getEmployeeType();
// Concrete method
public String getName() {
return name;
}
public String getEmployeeId() {
return employeeId;
}
private String generateEmployeeId() {
return "EMP" + System.currentTimeMillis() % 10000;
}
}
class FullTimeEmployee extends Employee {
private double baseSalary;
private double bonus;
public FullTimeEmployee(String name, double baseSalary, double bonus) {
super(name);
this.baseSalary = baseSalary;
this.bonus = bonus;
}
@Override
public double calculateSalary() {
return baseSalary + bonus;
}
@Override
public double calculateBonus() {
return bonus;
}
@Override
public String getEmployeeType() {
return "Full-Time";
}
// Full-time specific method
public double calculateAnnualBonus() {
return baseSalary * 0.1;
}
}
class PartTimeEmployee extends Employee {
private double hourlyRate;
private int hoursWorked;
public PartTimeEmployee(String name, double hourlyRate, int hoursWorked) {
super(name);
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
}
@Override
public double calculateSalary() {
return hourlyRate * hoursWorked;
}
@Override
public double calculateBonus() {
return hourlyRate * 10; // Fixed bonus for part-time
}
@Override
public String getEmployeeType() {
return "Part-Time";
}
// Part-time specific method
public double calculateOvertime(int overtimeHours) {
return hourlyRate * 1.5 * overtimeHours;
}
}
class Contractor extends Employee {
private double hourlyRate;
private int hoursWorked;
public Contractor(String name, double hourlyRate, int hoursWorked) {
super(name);
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
}
@Override
public double calculateSalary() {
return hourlyRate * hoursWorked;
}
@Override
public double calculateBonus() {
return 0; // Contractors don't get bonuses
}
@Override
public String getEmployeeType() {
return "Contractor";
}
// Contractor specific method
public double calculateProjectFee(double projectRate, int projectHours) {
return projectRate * projectHours;
}
}
class EmployeeManager {
private List<Employee> employees = new ArrayList<>();
public void addEmployee(Employee employee) {
employees.add(employee);
}
// Polymorphic payroll processing
public void processPayroll() {
System.out.println("=== PROCESSING PAYROLL ===");
double totalPayroll = 0;
for (Employee employee : employees) {
double salary = employee.calculateSalary();
double bonus = employee.calculateBonus();
double total = salary + bonus;
System.out.printf("%s (%s): $%.2f (Salary: $%.2f, Bonus: $%.2f)%n",
employee.getName(), employee.getEmployeeType(),
total, salary, bonus);
totalPayroll += total;
}
System.out.printf("Total Payroll: $%.2f%n", totalPayroll);
System.out.println();
}
public void generateReports() {
System.out.println("=== EMPLOYEE REPORTS ===");
for (Employee employee : employees) {
System.out.printf("ID: %s, Name: %s, Type: %s, Salary: $%.2f%n",
employee.getEmployeeId(), employee.getName(),
employee.getEmployeeType(), employee.calculateSalary());
}
System.out.println();
}
}
// E-commerce System
class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() { return name; }
public double getPrice() { return price; }
}
interface PaymentMethod {
void processPayment(double amount);
String getPaymentMethodName();
boolean isPaymentSuccessful();
}
class CreditCardPayment implements PaymentMethod {
@Override
public void processPayment(double amount) {
System.out.println("Processing credit card payment of $" + amount);
System.out.println("Validating card... Charging amount...");
System.out.println("Credit card payment successful!");
}
@Override
public String getPaymentMethodName() {
return "Credit Card";
}
@Override
public boolean isPaymentSuccessful() {
return true;
}
}
class PayPalPayment implements PaymentMethod {
@Override
public void processPayment(double amount) {
System.out.println("Processing PayPal payment of $" + amount);
System.out.println("Redirecting to PayPal... Authorizing payment...");
System.out.println("PayPal payment successful!");
}
@Override
public String getPaymentMethodName() {
return "PayPal";
}
@Override
public boolean isPaymentSuccessful() {
return true;
}
}
class CryptoPayment implements PaymentMethod {
@Override
public void processPayment(double amount) {
System.out.println("Processing cryptocurrency payment of $" + amount);
System.out.println("Converting to BTC... Confirming blockchain transaction...");
System.out.println("Cryptocurrency payment successful!");
}
@Override
public String getPaymentMethodName() {
return "Cryptocurrency";
}
@Override
public boolean isPaymentSuccessful() {
return true;
}
}
class ShoppingCart {
private List<Product> items = new ArrayList<>();
public void addItem(Product product) {
items.add(product);
}
public double calculateTotal() {
return items.stream().mapToDouble(Product::getPrice).sum();
}
// Polymorphic checkout - accepts any PaymentMethod
public void checkout(PaymentMethod paymentMethod) {
double total = calculateTotal();
System.out.println("\n=== CHECKOUT ===");
System.out.println("Items in cart: " + items.size());
System.out.println("Total amount: $" + total);
paymentMethod.processPayment(total);
if (paymentMethod.isPaymentSuccessful()) {
System.out.println("Order completed using " + paymentMethod.getPaymentMethodName());
items.clear();
} else {
System.out.println("Payment failed. Please try again.");
}
System.out.println();
}
}
// Vehicle Rental System
abstract class Vehicle {
protected String model;
protected int year;
protected boolean isRented;
public Vehicle(String model, int year) {
this.model = model;
this.year = year;
this.isRented = false;
}
// Abstract methods
public abstract double calculateRentalCost(int days);
public abstract String getVehicleType();
public abstract void displayFeatures();
// Concrete methods
public String getModel() { return model; }
public int getYear() { return year; }
public boolean isRented() { return isRented; }
public void rent() {
if (!isRented) {
isRented = true;
System.out.println(model + " has been rented.");
} else {
System.out.println(model + " is already rented.");
}
}
public void returnVehicle() {
if (isRented) {
isRented = false;
System.out.println(model + " has been returned.");
} else {
System.out.println(model + " was not rented.");
}
}
}
class Car extends Vehicle {
private int passengerCapacity;
public Car(String model, int year, int passengerCapacity) {
super(model, year);
this.passengerCapacity = passengerCapacity;
}
@Override
public double calculateRentalCost(int days) {
return 50.0 * days; // $50 per day
}
@Override
public String getVehicleType() {
return "Car";
}
@Override
public void displayFeatures() {
System.out.println("Car Features: " + passengerCapacity + " passengers, AC, Radio");
}
// Car-specific method
public void enableChildLock() {
System.out.println("Child safety locks enabled");
}
}
class Motorcycle extends Vehicle {
private int engineCapacity;
public Motorcycle(String model, int year, int engineCapacity) {
super(model, year);
this.engineCapacity = engineCapacity;
}
@Override
public double calculateRentalCost(int days) {
return 30.0 * days; // $30 per day
}
@Override
public String getVehicleType() {
return "Motorcycle";
}
@Override
public void displayFeatures() {
System.out.println("Motorcycle Features: " + engineCapacity + "cc engine, Helmet included");
}
// Motorcycle-specific method
public void wheelie() {
System.out.println("Performing wheelie! (Please drive safely)");
}
}
class Truck extends Vehicle {
private double cargoCapacity;
public Truck(String model, int year, double cargoCapacity) {
super(model, year);
this.cargoCapacity = cargoCapacity;
}
@Override
public double calculateRentalCost(int days) {
return 80.0 * days; // $80 per day
}
@Override
public String getVehicleType() {
return "Truck";
}
@Override
public void displayFeatures() {
System.out.println("Truck Features: " + cargoCapacity + "kg cargo capacity, Tow hitch");
}
// Truck-specific method
public void loadCargo(double weight) {
if (weight <= cargoCapacity) {
System.out.println("Cargo loaded: " + weight + "kg");
} else {
System.out.println("Cargo exceeds capacity!");
}
}
}
class RentalService {
private List<Vehicle> rentedVehicles = new ArrayList<>();
private double totalRevenue = 0;
// Polymorphic vehicle rental
public void rentVehicle(Vehicle vehicle, int days) {
System.out.println("=== RENTING VEHICLE ===");
vehicle.displayFeatures();
double cost = vehicle.calculateRentalCost(days);
System.out.printf("Rental cost for %d days: $%.2f%n", days, cost);
vehicle.rent();
rentedVehicles.add(vehicle);
totalRevenue += cost;
System.out.println();
}
public void displayRentalSummary() {
System.out.println("=== RENTAL SUMMARY ===");
System.out.println("Total vehicles rented: " + rentedVehicles.size());
System.out.printf("Total revenue: $%.2f%n", totalRevenue);
for (Vehicle vehicle : rentedVehicles) {
System.out.printf("- %s %s (%s)%n",
vehicle.getVehicleType(), vehicle.getModel(), vehicle.getYear());
}
System.out.println();
}
}
// Database System
interface Database {
void connect();
void disconnect();
void executeQuery(String query);
void commitTransaction();
void rollbackTransaction();
String getDatabaseType();
}
class MySQLDatabase implements Database {
@Override
public void connect() {
System.out.println("Connecting to MySQL database...");
}
@Override
public void disconnect() {
System.out.println("Disconnecting from MySQL database...");
}
@Override
public void executeQuery(String query) {
System.out.println("Executing MySQL query: " + query);
}
@Override
public void commitTransaction() {
System.out.println("Committing MySQL transaction...");
}
@Override
public void rollbackTransaction() {
System.out.println("Rolling back MySQL transaction...");
}
@Override
public String getDatabaseType() {
return "MySQL";
}
// MySQL specific method
public void enableBinaryLogging() {
System.out.println("MySQL binary logging enabled");
}
}
class PostgreSQLDatabase implements Database {
@Override
public void connect() {
System.out.println("Connecting to PostgreSQL database...");
}
@Override
public void disconnect() {
System.out.println("Disconnecting from PostgreSQL database...");
}
@Override
public void executeQuery(String query) {
System.out.println("Executing PostgreSQL query: " + query);
}
@Override
public void commitTransaction() {
System.out.println("Committing PostgreSQL transaction...");
}
@Override
public void rollbackTransaction() {
System.out.println("Rolling back PostgreSQL transaction...");
}
@Override
public String getDatabaseType() {
return "PostgreSQL";
}
// PostgreSQL specific method
public void enableReplication() {
System.out.println("PostgreSQL replication enabled");
}
}
class MongoDB implements Database {
@Override
public void connect() {
System.out.println("Connecting to MongoDB...");
}
@Override
public void disconnect() {
System.out.println("Disconnecting from MongoDB...");
}
@Override
public void executeQuery(String query) {
System.out.println("Executing MongoDB operation: " + query);
}
@Override
public void commitTransaction() {
System.out.println("MongoDB doesn't support traditional transactions");
}
@Override
public void rollbackTransaction() {
System.out.println("MongoDB doesn't support rollback in same way");
}
@Override
public String getDatabaseType() {
return "MongoDB";
}
// MongoDB specific method
public void createCollection(String name) {
System.out.println("Creating MongoDB collection: " + name);
}
}
class DatabaseManager {
// Polymorphic database operations
public void performDatabaseOperations(Database database) {
System.out.println("=== " + database.getDatabaseType() + " OPERATIONS ===");
database.connect();
database.executeQuery("SELECT * FROM users");
database.commitTransaction();
// Database-specific operations
if (database instanceof MySQLDatabase) {
((MySQLDatabase) database).enableBinaryLogging();
} else if (database instanceof PostgreSQLDatabase) {
((PostgreSQLDatabase) database).enableReplication();
} else if (database instanceof MongoDB) {
((MongoDB) database).createCollection("users");
}
database.disconnect();
System.out.println();
}
}
Output:
```
=== REAL-WORLD POLYMORPHISM APPLICATIONS ===
=== EMPLOYEE MANAGEMENT SYSTEM ===
=== PROCESSING PAYROLL ===
Alice (Full-Time): $55000.00 (Salary: $55000.00, Bonus: $5000.00)
Bob (Part-Time): $4000.00 (Salary: $4000.00, Bonus: $250.00)
Charlie (Contractor): $15000.00 (Salary: $15000.00, Bonus: $0.00)
Total Payroll: $74000.00
=== EMPLOYEE REPORTS ===