Reference type vs object type
32 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)One object can be reached through variables of several types at once. The object's type never changes; each variable's type decides what the compiler lets you do with it. That split explains every cast in this module.
One object, several reference types
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.
A UpiPayment object can sit behind a UpiPayment, a Payment and an Object variable at the same time, as in Upcasting (opens in a new tab). Each variable is a different view of the same object.
Example 1 · Three views of one payment
class Payment { void pay(int amount) { System.out.println("Paid Rs. " + amount); }}
class UpiPayment extends Payment { String upiId = "aarav@okbank";
@Override void pay(int amount) { System.out.println("UPI: Rs. " + amount + " from " + upiId); }
void showUpiId() { System.out.println("UPI ID: " + upiId); }}
public class ViewsDemo { public static void main(String[] args) { UpiPayment u = new UpiPayment(); Payment p = u; Object o = u; u.showUpiId(); p.pay(250); System.out.println(u == p && p == o); System.out.println(o.getClass().getSimpleName()); }}UPI ID: aarav@okbank UPI: Rs. 250 from aarav@okbank true UpiPayment
What this code does
Payment p = u;andObject o = u;copy the reference, not the object. All three variables point to oneUpiPayment, so==givestrue.p.pay(250)runs the UPI version, ando.getClass()still reportsUpiPayment. The view changed; the object did not.
The object type is fixed for the life of the object. What differs is the list of calls each view allows: u sees everything, p sees only what Payment declares, and o sees only Object methods such as toString() and equals().
The compiler does not track the object
After Payment p = new UpiPayment(); you know p holds a UPI payment. The compiler does not: it checks every line using only the declared type of each variable.
Example 2 · Mistake: the compiler forgot it was a UPI payment
class Payment { void pay(int amount) { System.out.println("Paid Rs. " + amount); }}
class UpiPayment extends Payment { void showUpiId() { System.out.println("UPI ID: aarav@okbank"); }}
public class ForgetDemo { public static void main(String[] args) { Payment p = new UpiPayment(); UpiPayment u = p; Object o = p; o.pay(100); }}ForgetDemo.java:16: error: incompatible types: Payment cannot be converted to UpiPayment
UpiPayment u = p;
^
ForgetDemo.java:18: error: cannot find symbol
o.pay(100);
^
symbol: method pay(int)
location: variable o of type Object
2 errorsWhat this code does
- Line 16: javac knows only
Payment p, so it refuses to putpinto aUpiPaymentvariable, even though this object is a UPI payment. - Line 18:
ois declared asObject, andObjecthas nopay(int). The object behindocould pay, but the compiler never looks at the object.
This is why going down to a narrower view needs a cast, the topic of Downcasting and ClassCastException (opens in a new tab). Going up to a wider view, like Object o = p;, never needs one.
Overloads are picked by the reference type
A billing class has two receipt methods: one takes a Payment, one takes a UpiPayment. Which runs for a Payment p that holds a UPI payment? The compiler picks overloads, so it goes by the reference type.
Example 3 · Overload by view, override by object
class Payment { String mode() { return "Cash"; }}
class UpiPayment extends Payment { @Override String mode() { return "UPI"; }}
public class ReceiptDemo { static void receipt(Payment p) { System.out.println("General receipt, mode " + p.mode()); }
static void receipt(UpiPayment u) { System.out.println("UPI receipt, mode " + u.mode()); }
public static void main(String[] args) { UpiPayment u = new UpiPayment(); Payment p = u; receipt(u); receipt(p); }}UPI receipt, mode UPI General receipt, mode UPI
What this code does
- Both calls pass the same object.
receipt(u)matchesreceipt(UpiPayment);receipt(p)matchesreceipt(Payment), because javac picks an overload from the argument's declared type. - Inside,
mode()is overridden, so it follows the object and givesUPIboth times. Overloads look at the view; overrides look at the object.
The same rule decides between println(Object) and println(String): with Object o = "Hi";, System.out.println(o) picks println(Object), which still prints Hi because toString() follows the object. Overloading vs overriding (opens in a new tab) compares the two ideas in general.
Predict the output
Which overload, which override?
Read the code and pick what it prints.
Round 1 of 3
f holds a LateFee. Which show runs, and which amount does it print?
Expressions have a reference type too
Not only variables have a declared type. A method call, an array element and a ? : expression each have one, and the compiler uses it exactly like a variable's type.
Example 4 · The type of a call, an element and a ?: expression
class Ticket { int fare() { return 300; }}
class AcTicket extends Ticket { @Override int fare() { return 1700; }
String berth() { return "Lower berth"; }}
public class ExpressionTypes { static Ticket book(boolean ac) { if (ac) { return new AcTicket(); } return new Ticket(); }
public static void main(String[] args) { Ticket[] trip = { book(true), book(false) }; boolean tatkal = true; Ticket next = tatkal ? new AcTicket() : new Ticket(); System.out.println(book(true).fare()); System.out.println(trip[0].fare() + trip[1].fare()); System.out.println(next.getClass().getSimpleName()); }}1700 2000 AcTicket
What this code does
book(true)has the typeTicket, the method's return type, sobook(true).fare()compiles; the AC object'sfare()runs and gives 1700.trip[0]has the element typeTicket. The? :expression mixesAcTicketandTicket, sonextmust be aTicketvariable, while the object inside is anAcTicket.
Example 5 · Mistake: a child-only method on an expression
class Ticket { int fare() { return 300; }}
class AcTicket extends Ticket { @Override int fare() { return 1700; }
String berth() { return "Lower berth"; }}
public class BerthDemo { static Ticket book(boolean ac) { if (ac) { return new AcTicket(); } return new Ticket(); }
public static void main(String[] args) { Ticket[] trip = { book(true) }; System.out.println(book(true).berth()); System.out.println(trip[0].berth()); }}BerthDemo.java:28: error: cannot find symbol
System.out.println(book(true).berth());
^
symbol: method berth()
location: class Ticket
BerthDemo.java:29: error: cannot find symbol
System.out.println(trip[0].berth());
^
symbol: method berth()
location: class Ticket
2 errorsWhat this code does
- Both lines fail for one reason:
book(true)andtrip[0]have the typeTicket, andTickethas noberth(). - The message says
location: class Ticket, the type of the expression, not of the object. Fix it with aberth()method inTicket, or with anAcTicketvariable, which needs a cast.
A method call has its method's return type. An array element has the array's element type. A ? : that mixes AcTicket and Ticket has the type of their common parent, Ticket.
Pick the widest reference type that works
So which type should a variable, parameter or field have? Use the widest type, the one nearest the top, that still has every method the code calls. Use a child type only when you need a child-only member.
Example 6 · A canteen counter that accepts every payment
class Payment { int amount;
Payment(int amount) { this.amount = amount; }
String mode() { return "Cash"; }}
class UpiPayment extends Payment { String upiId;
UpiPayment(int amount, String upiId) { super(amount); this.upiId = upiId; }
@Override String mode() { return "UPI"; }}
class CardPayment extends Payment { CardPayment(int amount) { super(amount); }
@Override String mode() { return "Card"; }}
public class CanteenCounter { static int total = 0;
static void accept(Payment p) { total = total + p.amount; System.out.println(p.mode() + ": Rs. " + p.amount); }
static void showUpi(UpiPayment u) { System.out.println("Paid from " + u.upiId); }
public static void main(String[] args) { UpiPayment upi = new UpiPayment(60, "diya@okicici"); accept(upi); accept(new CardPayment(120)); accept(new Payment(30)); showUpi(upi); System.out.println("Total: Rs. " + total); }}UPI: Rs. 60 Card: Rs. 120 Cash: Rs. 30 Paid from diya@okicici Total: Rs. 210
What this code does
acceptneeds onlyamountandmode(), which everyPaymenthas, so aPaymentparameter takes all three kinds.showUpireadsupiId, which only a UPI payment has, so its parameter must beUpiPayment.mainkeepsupiin aUpiPaymentvariable so it can pass it to both.
A wide type keeps code open: a new WalletPayment class works with accept at once. A narrow type is a promise you really need: it lets showUpi read upiId without any cast.
Next step
Check your understanding
12 quick questions