Skip to lesson

Parent reference, child object (upcasting)

A checkout page must accept UPI, card and net banking payments. Writing one method per payment type would never end.

A child object in a parent variable

Upcasting is storing a child object in a variable of its parent type, like Payment p = new UpiPayment();. It is automatic and always safe, because a child is a kind of its parent. The object itself does not change.

Inheritance makes every UpiPayment a Payment (the IS-A test). So wherever Java expects a Payment, a UpiPayment object fits, with no extra syntax.

Example 1 · Parent variable, child object

UpcastDemo.javaJava
class Payment {    void pay(int amount) {        System.out.println("Paying Rs. " + amount);    }
    void receipt() {        System.out.println("Receipt sent by SMS");    }}
class UpiPayment extends Payment {    @Override    void pay(int amount) {        System.out.println("UPI: Rs. " + amount + " sent");    }}
public class UpcastDemo {    public static void main(String[] args) {        Payment p = new UpiPayment();        p.pay(500);        p.receipt();    }}
Output
UPI: Rs. 500 sent
Receipt sent by SMS

What this code does

  • Payment p = new UpiPayment(); upcasts automatically: the variable is a Payment, the object is a UpiPayment.
  • pay is overridden, so the UPI version runs. receipt is not, so the inherited version runs.

"Up" means up the class tree, from the child towards the parent. You never write a cast for it: Java does it on every =, every method argument and every return that needs the parent type.

Reference type and object type

Reference type is the declared type of a variable; object type is the class the object was created from with new. In Payment p = new UpiPayment(); the reference type is Payment and the object type is UpiPayment.

The two types have two jobs. The compiler checks every call against the reference type; the JVM uses the object type to pick which overridden version runs.

Payment p = new UpiPayment(). The variable p on the stack has the reference type Payment and points to one UpiPayment object on the heap. The reference type decides what you may call (checked by javac); the object type decides which version of pay runs (chosen by the JVM).

Example 2 · Mistake: calling a child-only method

ChildOnlyDemo.javaJava
class Payment {    void pay(int amount) {        System.out.println("Paying Rs. " + amount);    }}
class UpiPayment extends Payment {    @Override    void pay(int amount) {        System.out.println("UPI: Rs. " + amount);    }
    void showUpiId() {        System.out.println("aarav@okbank");    }}
public class ChildOnlyDemo {    public static void main(String[] args) {        Payment p = new UpiPayment();        p.pay(500);        p.showUpiId();    }}
Sample compiler output
ChildOnlyDemo.java:22: error: cannot find symbol
        p.showUpiId();
         ^
  symbol:   method showUpiId()
  location: variable p of type Payment
1 error

What this code does

  • The message says it: "location: variable p of type Payment". The compiler checks the reference type, and Payment has no showUpiId().
  • The object really is a UpiPayment, but that does not matter at compile time. With UpiPayment u = new UpiPayment(); both calls compile.

p could hold a UpiPayment now and a CardPayment later, so the compiler allows only what every Payment has. To call showUpiId(), use a UpiPayment variable. Getting the child type back from a parent variable is Downcasting (opens in a new tab), in a later module; good design rarely needs it.

The other direction does not compile

Every UPI payment is a payment, but not every payment is a UPI payment. So a child-type variable cannot take a plain parent object.

Example 3 · Mistake: the other direction

ReverseDemo.javaJava
class Payment {    void pay(int amount) {        System.out.println("Paying Rs. " + amount);    }}
class UpiPayment extends Payment {    @Override    void pay(int amount) {        System.out.println("UPI: Rs. " + amount);    }}
public class ReverseDemo {    public static void main(String[] args) {        UpiPayment u = new Payment();        u.pay(500);    }}
Sample compiler output
ReverseDemo.java:16: error: incompatible types: Payment cannot be converted to UpiPayment
        UpiPayment u = new Payment();
                       ^
1 error

What this code does

  • Child object → parent variable is upcasting and always fine. Parent object → child variable is never allowed.
  • The fix depends on what you need: Payment p = new Payment(); for a plain payment, or new UpiPayment() for a UPI one.

A UpiPayment variable promises every UPI method, such as showUpiId(). A plain Payment object cannot keep that promise, so javac stops it at once.

Parent-type arrays, parameters and return types

The real power shows when many objects share one type. A Payment[] array, a Payment parameter or a Payment return type accepts every child, and each object still runs its own pay.

Example 4 · One array, many payment types

ArrayDemo.javaJava
class Payment {    void pay(int amount) {        System.out.println("Cash: Rs. " + amount);    }}
class UpiPayment extends Payment {    @Override    void pay(int amount) {        System.out.println("UPI: Rs. " + amount);    }}
class CardPayment extends Payment {    @Override    void pay(int amount) {        System.out.println("Card: Rs. " + amount);    }}
public class ArrayDemo {    public static void main(String[] args) {        Payment[] payments = { new UpiPayment(), new CardPayment(), new Payment() };        int[] amounts = { 250, 1800, 60 };        for (int i = 0; i < payments.length; i++) {            payments[i].pay(amounts[i]);        }    }}
Output
UPI: Rs. 250
Card: Rs. 1800
Cash: Rs. 60

What this code does

  • The array type is Payment[], so each slot can hold any kind of payment. Each object is upcast when it is stored.
  • The loop has one call, payments[i].pay(...), yet three different versions run.

Example 5 · A method with a parent parameter

AnnounceDemo.javaJava
class Notification {    void send(String msg) {        System.out.println("Notice board: " + msg);    }}
class SmsNotification extends Notification {    @Override    void send(String msg) {        System.out.println("SMS: " + msg);    }}
class EmailNotification extends Notification {    @Override    void send(String msg) {        System.out.println("Email: " + msg);    }}
public class AnnounceDemo {    static void announce(Notification n) {        n.send("Holiday on Friday");    }
    public static void main(String[] args) {        announce(new SmsNotification());        announce(new EmailNotification());        announce(new Notification());    }}
Output
SMS: Holiday on Friday
Email: Holiday on Friday
Notice board: Holiday on Friday

What this code does

  • Passing an SmsNotification to a Notification parameter is upcasting, done automatically.
  • announce is written once. A new PushNotification class would work with it without any change.

Example 6 · A method that returns the parent type

ChooseDemo.javaJava
class Payment {    void pay(int amount) {        System.out.println("Cash: Rs. " + amount);    }}
class UpiPayment extends Payment {    @Override    void pay(int amount) {        System.out.println("UPI: Rs. " + amount);    }}
class CardPayment extends Payment {    @Override    void pay(int amount) {        System.out.println("Card: Rs. " + amount);    }}
public class ChooseDemo {    static Payment choose(String mode) {        if (mode.equals("UPI")) {            return new UpiPayment();        } else if (mode.equals("CARD")) {            return new CardPayment();        }        return new Payment();    }
    public static void main(String[] args) {        Payment p = choose("UPI");        p.pay(499);        choose("CASH").pay(120);    }}
Output
UPI: Rs. 499
Cash: Rs. 120

What this code does

  • choose promises a Payment, so it may return any child object. The if that picks a type lives in this one place only.
  • The caller works with a Payment and never needs to know which class it got.

Write code against the parent type wherever you can. A new child class then plugs into every such array, method and loop without one line changing. Why each object runs its own version is the topic of Dynamic method dispatch (opens in a new tab).

Next step

Check your understanding

12 quick questions