Skip to lesson

Reference type vs object type

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.

One UpiPayment object on the heap with three references to it. UpiPayment u may call pay, showUpiId and toString; Payment p may call pay and toString; Object o may call only Object methods such as toString and equals. It is one object, so u == p is true.

Example 1 · Three views of one payment

ViewsDemo.javaJava
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());    }}
Output
UPI ID: aarav@okbank
UPI: Rs. 250 from aarav@okbank
true
UpiPayment

What this code does

  • Payment p = u; and Object o = u; copy the reference, not the object. All three variables point to one UpiPayment, so == gives true.
  • p.pay(250) runs the UPI version, and o.getClass() still reports UpiPayment. 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

ForgetDemo.javaJava
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);    }}
Sample compiler output
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 errors

What this code does

  • Line 16: javac knows only Payment p, so it refuses to put p into a UpiPayment variable, even though this object is a UPI payment.
  • Line 18: o is declared as Object, and Object has no pay(int). The object behind o could 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

ReceiptDemo.javaJava
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);    }}
Output
UPI receipt, mode UPI
General receipt, mode UPI

What this code does

  • Both calls pass the same object. receipt(u) matches receipt(UpiPayment); receipt(p) matches receipt(Payment), because javac picks an overload from the argument's declared type.
  • Inside, mode() is overridden, so it follows the object and gives UPI both 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?

class Fee {
int amount() {
return 1000;
}
}
class LateFee extends Fee {
@Override
int amount() {
return 1200;
}
}
public class FeeDesk {
static void show(Fee f) {
System.out.println("Fee " + f.amount());
}
static void show(LateFee f) {
System.out.println("LateFee " + f.amount());
}
public static void main(String[] args) {
Fee f = new LateFee();
show(f);
}
}

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

ExpressionTypes.javaJava
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());    }}
Output
1700
2000
AcTicket

What this code does

  • book(true) has the type Ticket, the method's return type, so book(true).fare() compiles; the AC object's fare() runs and gives 1700.
  • trip[0] has the element type Ticket. The ? : expression mixes AcTicket and Ticket, so next must be a Ticket variable, while the object inside is an AcTicket.

Example 5 · Mistake: a child-only method on an expression

BerthDemo.javaJava
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());    }}
Sample compiler output
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 errors

What this code does

  • Both lines fail for one reason: book(true) and trip[0] have the type Ticket, and Ticket has no berth().
  • The message says location: class Ticket, the type of the expression, not of the object. Fix it with a berth() method in Ticket, or with an AcTicket variable, 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

CanteenCounter.javaJava
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);    }}
Output
UPI: Rs. 60
Card: Rs. 120
Cash: Rs. 30
Paid from diya@okicici
Total: Rs. 210

What this code does

  • accept needs only amount and mode(), which every Payment has, so a Payment parameter takes all three kinds.
  • showUpi reads upiId, which only a UPI payment has, so its parameter must be UpiPayment. main keeps upi in a UpiPayment variable 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