Java Polymorphism Example

Different definitions of Polymorphism are:

  1. Polymorphism lets perform a single action in different ways.
  2. Polymorphism allows you to define one interface and have multiple implementations
  3. We can create functions or reference variables that behaves differently in a different programmatic context.
  4. Polymorphism means many forms.

Java Polymorphism Example

In this Payment Processing Example, applying runtime polymorphism and it can have many forms at runtime. Refer below source code the single payment "p" instance can be used to pay by cash and credit card, payment p instance takes many forms here.

public class Polymorphism {

    public static void main(String[] args) {
        // Here the runtime polymorphism fundamental is not applied, 
        // as it is of single CashPayment form
        CashPayment c = new CashPayment();
        c.pay();

        // Now the initialization is done using runtime polymorphism and 
        // it can have many forms at runtime
        // Single payment "p" instance can be used to pay by cash and credit card
        Payment p = new CashPayment();
        p.pay(); // Pay by cash

        p = new CreditPayment();
        p.pay(); // Pay by creditcard
    }

}

/**
 * This represents payment interface
 */
interface Payment {
    public void pay();
}

/**
 * Cash IS-A Payment type
 * 
 * @author tirthalp
 * 
 */
class CashPayment implements Payment {

    // method overriding
    @Override
    public void pay() {
        System.out.println("This is cash payment");
    }

}

/**
 * Creditcard IS-A Payment type
 */
class CreditPayment implements Payment {

    // method overriding
    @Override
    public void pay() {
        System.out.println("This is credit card payment");
    }

}

Reference


Related Java OOPS Examples


Comments