Java: Polymorphism and Abstraction

Polymorphism is a core OOP feature that makes code more flexible and extensible.

1. What is Polymorphism

Polymorphism means the same method behaves differently on different objects.

(1) Benefits of Polymorphism

Benefit Description
Flexibility Same interface, different implementations
Extensibility Adding new subclasses doesn't require modifying parent code
Simplified code Use parent class references to operate on child objects

2. Upcasting

A child object can be assigned to a parent class reference.

TEXT 📖 Display only
Animal animal = new Dog();  // Upcasting

▶ Example: Upcasting

JAVA
public class Animal {
    public void eat() {
        System.out.println("Animal is eating");
    }
}

public class Dog extends Animal {
    @Override
    public void eat() {
        System.out.println("Dog is chewing a bone");
    }
    
    public void bark() {
        System.out.println("Barking");
    }
}

public class PolymorphismDemo {
    public static void main(String[] args) {
        Animal animal = new Dog();  // Upcasting
        animal.eat();  // Dog is chewing a bone (calls Dog's eat)
        // animal.bark();  // Compile error! Parent reference can only access parent methods
    }
}
▶ Try it Yourself

3. Dynamic Binding

At runtime, the method is called based on the actual object type, not the compile-time type.

▶ Example: Dynamic Binding

TEXT 📖 Display only
public class Animal {
    public void speak() {
        System.out.println("Animal makes a sound");
    }
}

public class Dog extends Animal {
    @Override
    public void speak() {
        System.out.println("Woof woof");
    }
}

public class Cat extends Animal {
    @Override
    public void speak() {
        System.out.println("Meow meow");
    }
}

public class DynamicBinding {
    public static void makeSound(Animal animal) {
        animal.speak();  // Decided at runtime which speak to call
    }
    
    public static void main(String[] args) {
        makeSound(new Dog());  // Woof woof
        makeSound(new Cat());  // Meow meow
    }
}

4. Abstract Classes

Abstract classes cannot be instantiated—they can only be inherited.

(1) Abstract Methods

Methods without a body that subclasses must implement.

JAVA
public abstract class Shape {
    // Abstract method: no body
    public abstract double area();
    
    // Regular method: has body
    public void display() {
        System.out.println("Area: " + area());
    }
}

▶ Example: Abstract Class

TEXT 📖 Display only
public abstract class Shape {
    protected String name;
    
    public Shape(String name) {
        this.name = name;
    }
    
    // Abstract methods
    public abstract double area();
    public abstract double perimeter();
    
    public void display() {
        System.out.println(name + " - Area: " + area() + ", Perimeter: " + perimeter());
    }
}

public class Circle extends Shape {
    private double radius;
    
    public Circle(double radius) {
        super("Circle");
        this.radius = radius;
    }
    
    @Override
    public double area() {
        return Math.PI * radius * radius;
    }
    
    @Override
    public double perimeter() {
        return 2 * Math.PI * radius;
    }
}

public class Rectangle extends Shape {
    private double width, height;
    
    public Rectangle(double width, double height) {
        super("Rectangle");
        this.width = width;
        this.height = height;
    }
    
    @Override
    public double area() {
        return width * height;
    }
    
    @Override
    public double perimeter() {
        return 2 * (width + height);
    }
}

public class ShapeDemo {
    public static void main(String[] args) {
        Shape circle = new Circle(5);
        Shape rect = new Rectangle(4, 6);
        
        circle.display();  // Circle - Area: 78.54, Perimeter: 31.42
        rect.display();    // Rectangle - Area: 24.0, Perimeter: 20.0
    }
}

5. Interfaces

Interfaces define a set of rules that implementing classes must follow.

(1) Interface Definition

JAVA
public interface InterfaceName {
    // Constants (default public static final)
    int MAX_SIZE = 100;
    
    // Abstract methods (default public abstract)
    void method1();
    int method2(int a);
}

(2) Interface Implementation

TEXT 📖 Display only
public class ClassName implements InterfaceName {
    @Override
    public void method1() {
        // Implementation
    }
    
    @Override
    public int method2(int a) {
        return a;
    }
}

▶ Example: Interface

JAVA
public interface Flyable {
    void fly();
}

public interface Swimmable {
    void swim();
}

public class Duck implements Flyable, Swimmable {
    @Override
    public void fly() {
        System.out.println("Duck is flying");
    }
    
    @Override
    public void swim() {
        System.out.println("Duck is swimming");
    }
}

public class InterfaceDemo {
    public static void main(String[] args) {
        Duck duck = new Duck();
        duck.fly();   // Duck is flying
        duck.swim();  // Duck is swimming
        
        // Interface reference
        Flyable flyer = new Duck();
        flyer.fly();
    }
}
▶ Try it Yourself

6. Interface vs Abstract Class

Feature Interface Abstract Class
Keyword interface abstract class
Implementation implements extends
Multiple implementation Supported Not supported
Constructors None Has constructors
Member variables Constants only Can have regular variables
Methods Abstract methods (pre-Java 8) Can have regular methods

7. Programming to Interfaces

JAVA
public interface Payment {
    void pay(double amount);
}

public class Alipay implements Payment {
    @Override
    public void pay(double amount) {
        System.out.println("Alipay payment: $" + amount);
    }
}

public class WechatPay implements Payment {
    @Override
    public void pay(double amount) {
        System.out.println("WeChat payment: $" + amount);
    }
}

public class PaymentDemo {
    // Program to interface
    public static void checkout(Payment payment, double amount) {
        payment.pay(amount);
    }
    
    public static void main(String[] args) {
        checkout(new Alipay(), 100);      // Alipay payment: $100.0
        checkout(new WechatPay(), 200);   // WeChat payment: $200.0
    }
}

8. ❓ Frequently Asked Questions

Q When should I use an abstract class vs an interface?
A Use abstract classes when you have shared state and behavior. Use interfaces when you only need to define a contract.
Q Can interfaces have method bodies?
A Yes, since Java 8, you can use the default keyword to define default methods.
Q Can I call child-specific methods after upcasting?
A No, you need to downcast (explicit cast) first.

❓ FAQ

Q What is dynamic dispatch?
A The JVM determines which overridden method to call at runtime based on the actual object type.
Q Can I downcast?
A Yes, with explicit casting. Use instanceof to check before downcasting to avoid ClassCastException.
Q What is the difference between overriding and overloading?
A Overriding redefines a parent method with the same signature; overloading has the same name but different parameters.

📖 Summary

📝 Exercises

  1. Animal hierarchy: Define an abstract Animal class with Dog and Cat subclasses, implement polymorphic calls
  2. Shape calculations: Define a Shape interface, implement Circle and Rectangle, calculate areas
  3. Payment system: Define a Payment interface, implement multiple payment methods

9. Next Lesson

In the next lesson, we'll learn about Advanced Interfaces and Lambda — interface features and Lambda expressions.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏