Parent reference, child object (upcasting)
34 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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(); }}UPI: Rs. 500 sent Receipt sent by SMS
What this code does
Payment p = new UpiPayment();upcasts automatically: the variable is aPayment, the object is aUpiPayment.payis overridden, so the UPI version runs.receiptis 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.
Example 2 · Mistake: calling a child-only method
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(); }}ChildOnlyDemo.java:22: error: cannot find symbol
p.showUpiId();
^
symbol: method showUpiId()
location: variable p of type Payment
1 errorWhat this code does
- The message says it: "location: variable p of type Payment". The compiler checks the reference type, and
Paymenthas noshowUpiId(). - The object really is a
UpiPayment, but that does not matter at compile time. WithUpiPayment 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
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); }}ReverseDemo.java:16: error: incompatible types: Payment cannot be converted to UpiPayment
UpiPayment u = new Payment();
^
1 errorWhat 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, ornew 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
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]); } }}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
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()); }}SMS: Holiday on Friday Email: Holiday on Friday Notice board: Holiday on Friday
What this code does
- Passing an
SmsNotificationto aNotificationparameter is upcasting, done automatically. announceis written once. A newPushNotificationclass would work with it without any change.
Example 6 · A method that returns the parent type
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); }}UPI: Rs. 499 Cash: Rs. 120
What this code does
choosepromises aPayment, so it may return any child object. Theifthat picks a type lives in this one place only.- The caller works with a
Paymentand 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