Which method runs and what compiles: the base for most other topics.
Open the interactive lessons →OOP: Inheritance, Polymorphism, Interfaces and Inner Classes past questions
Contents
- Constructors and super
- Override or overload?
- Dynamic dispatch
- final and private
- toString and equals
- Static type, casts and instanceof
- Abstract classes and interfaces
- Callbacks and private inner classes
1. Constructors and super
One new can run several constructors on one object.
the order in which an object of a subclass is built
A VipTicket is a kind of Ticket. It has the seat that every ticket has, plus a lounge number of its own. When you write new VipTicket(2), someone has to fill both fields. Which code does which part, and in what order?
Think of a house: the ground floor is built before the first floor, because the upper floor rests on it. Here the ground floor is the parent class. The analogy stops at one point: you still get one house, so one object, never a separate parent object.
Why this order? The child's code is allowed to use what the parent provides. That is only safe if the parent part is ready first. So Java makes the first line of every constructor hand control upwards: either super(...) (a constructor of the parent) or this(...) (another constructor of the same class, which in turn goes upwards).
On this JDK, this(...) or super(...) must be the first statement of a constructor. If you write neither, the compiler inserts super();, the parent's constructor with no arguments.
Here is the whole program. Read it once, then step through the picture.
Three constructors
class Ticket {
String seat;
Ticket() {
this("open");
System.out.println("Ticket()");
}
Ticket(String s) {
seat = s;
System.out.println("Ticket(String) " + s);
}
}
class VipTicket extends Ticket {
int lounge;
VipTicket(int n) {
super();
lounge = n;
System.out.println("VipTicket(int) " + n);
}
}
public class Main {
public static void main(String[] args) {
VipTicket t = new VipTicket(2);
System.out.println(t.seat + " / " + t.lounge);
}
}
One object, three constructors
newmakes one object with default field values, then entersVipTicket(int).- The first line,
super(), pauses this body and enters the parent constructor. this("open")hands over to another constructor of the same class. Still one object.- The deepest constructor finishes first: it fills
seatand prints. - Control returns to
Ticket(), which prints its own line. - Only now does the child body run: it sets
loungeand prints last. newhands back one reference, andmainstores it int.
Worked example: The line you did not write
Problem.
What does this program print?
class Lamp {
Lamp() { System.out.println("base ready"); }
}
class DeskLamp extends Lamp {
DeskLamp() { System.out.println("arm ready"); }
}
public class Main {
public static void main(String[] args) {
new DeskLamp();
}
}What is asked.
The printed lines, in order.
Idea.
Add the hidden super(); and then run from the top.
new DeskLamp()entersDeskLamp().DeskLamp()writes no first-line call, so the compiler has insertedsuper();.Lamp()runs and printsbase ready.- Control returns, and
DeskLamp()printsarm ready.
Answer.
base ready, then arm ready
Common mistake.
Thinking only the constructor named after new runs.
The Lamp program prints base ready and then arm ready.
Lampgets only a constructor with a parameter:Lamp(int w) { }replacesLamp(). What happens toDeskLamp?
It no longer compiles.. The insertedsuper();looks for a parent constructor with no arguments, and there is none.DeskLamp()becomesthis(3);followed by its print, andDeskLamp(int h) { System.out.println("height " + h); }is added. What prints?
It printsbase ready,height 3,arm ready..this(3)goes sideways first; the sideways constructor still gets the insertedsuper();. The parent runs once.Lamp()is markedprivate. Does the program compile?
It does not compile.. The child must call a parent constructor, and a private one is invisible to it.
Worked example: A private field in the parent
Problem.
FruitCrate must label itself. The field label is private in Crate. What prints?
class Crate {
private String label;
Crate(String label) { this.label = label; }
String label() { return label; }
}
class FruitCrate extends Crate {
int kg;
FruitCrate(String fruit, int kg) {
super(fruit + "-box");
this.kg = kg;
}
}
public class Main {
public static void main(String[] args) {
FruitCrate f = new FruitCrate("mango", 12);
System.out.println(f.label() + " " + f.kg);
}
}What is asked.
The printed line.
Idea.
A child sets a parent's private field only by passing a value to the parent's constructor.
FruitCrate("mango", 12)first callssuper("mango-box").Cratestores that text in its privatelabel.- Back in the child,
this.kg = kg;stores 12. label()is an inherited method, so it can read the private field for us.
Answer.
mango-box 12
Common mistake.
Writing label = fruit; in the child. The child cannot see a private field, so that line is rejected.
Sideways or upwards
this(...)
Calls another constructor of the same class.
Box() { this(10); }
Box(int s) { size = s; }super(...)
Calls a constructor of the parent class.
Box() { super(10); }The difference. The first word of the first line.
this(...) reuses your own class; super(...) builds the inherited part. A constructor can start with only one of them.
"The parent is fully built first" does not mean a parent constructor only runs parent code. If it calls a method that the child overrides, the child's body runs while the child's fields still hold their defaults.
The early call
class Frame {
Frame() { System.out.println("size seen: " + size()); }
int size() { return 1; }
}
class Poster extends Frame {
private int width = 40;
@Override
int size() { return width; }
}
public class Main {
public static void main(String[] args) {
Poster p = new Poster();
System.out.println("size now: " + p.size());
}
}2. Override or overload?
Two methods can share a name for two very different reasons.
how Java chooses among methods that share a name
A Tuba is a Horn. The parent can blow a number of times, blow(int), or blow a tune, blow(String). The tuba wants its own sound for one of the two. What happens to the other one, and how does Java know which you meant? The parent also has practice(), which calls blow(2). A call written like that inside a parent method is a call on the object itself, so a child's override answers it; the next lesson shows why.
Think of a form with a name and a number of blanks. "blow, one number blank" and "blow, one text blank" are different forms, even with the same title. A child can rewrite the answer to one form and leave the other untouched. The analogy stops at types: two forms can differ only in what kind of thing goes into a blank.
Why two mechanisms? The compiler must know, before the program runs, that some method accepts your arguments. So it chooses the signature from what is written. The object's class is unknown at that time, so the choice of body for that signature is left until the program runs.
Two steps for every call
| Step | When | Uses |
|---|---|---|
| 1. pick the signature | compile time | type of the variable and of each argument, as written |
| 2. pick the body | run time | class of the object |
Worked example: One override, one untouched
Problem.
What does this print?
class Horn {
String blow(int times) { return "toot x" + times; }
String blow(String tune) { return "toot " + tune; }
String practice() { return blow(2); }
}
class Tuba extends Horn {
@Override
String blow(int times) { return "oompah x" + times; }
}
public class Main {
public static void main(String[] args) {
Horn h = new Tuba();
System.out.println(h.practice());
System.out.println(h.blow("march"));
}
}What is asked.
Both lines.
Idea.
For each call, fix the signature first, then ask the object.
h.practice()is not overridden, so the body inHornruns and callsblow(2)on this object.- The argument
2is anint, so the signature isblow(int).Tubaoverrides it and returnsoompah x2. h.blow("march")fixes the signatureblow(String).Tubahas noblow(String), so the inherited body returnstoot march.
Answer.
oompah x2, then toot march
Common mistake.
Believing that overriding one blow replaces both.
The Horn program prints oompah x2 and toot march.
- The tuba's method becomes
String blow(long times)and@Overrideis removed. What prints for the first call?
It printstoot x2..blow(long)is a new overload. The callblow(2)written inHornfixesblow(int), which nobody overrides now. - Same change, but
@Overridestays. Compile or not?
It does not compile..@Overrideasks the compiler to confirm that a parent method is really being replaced. It is not. - The tuba's
blow(int)returnsintinstead ofString. Compile or not?
It does not compile.. The signature matches, so it is an override, and an override cannot swap the return type for an unrelated one.
Worked example: The written type of an argument
Problem.
The same text is passed twice. Does it land in the same bin?
class Sorter {
String take(Object o) { return "object bin"; }
String take(String s) { return "text bin"; }
}
public class Main {
public static void main(String[] args) {
Sorter s = new Sorter();
Object x = "pen";
System.out.println(s.take(x));
System.out.println(s.take("pen"));
}
}What is asked.
Both lines.
Idea.
Overloads are chosen from the argument's written type, never from the object.
xis written asObject, although it holds aString.- For
s.take(x)onlytake(Object)accepts anObject. - The literal
"pen"is written as aString, so both overloads accept it. - Of two that fit, Java takes the more specific one,
take(String).
Answer.
object bin, then text bin
Common mistake.
Expecting Java to look inside x at run time.
One type in the parameter list
Override
class Kid extends Dad {
void hum(String tune) { }
}Overload
class Kid extends Dad {
void hum(Object tune) { }
}The difference. String against Object, with Dad declaring hum(String).
Same signature replaces; a different parameter list adds a second method.
"The child's version wins" fails for a method the child only adds. Through a parent-typed variable the compiler never sees the added overload, even when it fits better.
Worked example: Same object, two answers
Problem.
Both variables hold a KitchenScale. Do both calls print the same?
class Scale {
String read(long grams) { return "base long"; }
}
class KitchenScale extends Scale {
@Override
String read(long grams) { return "kitchen long"; }
String read(int grams) { return "kitchen int"; }
}
public class Main {
public static void main(String[] args) {
Scale a = new KitchenScale();
KitchenScale b = new KitchenScale();
System.out.println(a.read(5));
System.out.println(b.read(5));
}
}What is asked.
Both lines.
Idea.
The variable's type limits which signatures can be chosen.
- For
a.read(5)the compiler searchesScale, which has onlyread(long). Theint5 is converted to the wider typelong. - At run time
KitchenScaleoverridesread(long), so the first line iskitchen long. - For
b.read(5)the compiler searchesKitchenScaleand findsread(int), an exact fit. - That body prints
kitchen int.
Answer.
kitchen long, then kitchen int
Common mistake.
Assuming the object alone decides.
3. Dynamic dispatch
The object answers method calls, whatever the variable is called.
which body runs when a parent-typed variable holds a child object
A café menu lists "drink: serve". The barista behind the counter holds whatever was actually made, perhaps a latte. When you ask for "serve", you get the latte's way of serving, although the menu only said "drink".
In code: Drink d = new Latte();. The left side is the menu entry, the static type. The right side is the thing made, the runtime class. Storing a child in a parent variable is an upcast; it changes nothing inside the object. The café analogy stops at fields, as you will see.
Why ask the object? Code written for Drink must keep working for drinks invented later. If the variable's type chose the body, a new subclass could never change how old code behaves. So Java checks the name early and chooses the body late.
Worked example: Call through the parent
Problem.
What does this print?
class Drink {
String kind = "plain";
static String shelf() { return "drink shelf"; }
String serve() { return "pour"; }
String order() { return "order: " + serve(); }
}
class Latte extends Drink {
String kind = "latte";
static String shelf() { return "coffee shelf"; }
@Override
String serve() { return "steam, pour"; }
String art() { return "heart"; }
}
public class Main {
public static void main(String[] args) {
Drink d = new Latte();
System.out.println(d.serve());
System.out.println(d.order());
}
}What is asked.
Both lines.
Idea.
Search for each body starting at the class Latte and walking upwards.
d.serve():Lattehasserve(), so it returnssteam, pour.d.order():Lattehas noorder(), so the search moves up toDrink.Drink.order()callsserve()onthis, which is still theLatte.- That inner call again finds
Latte.serve().
Answer.
steam, pour, then order: steam, pour
Common mistake.
Thinking a call written inside Drink must use Drink.serve().
The program prints steam, pour and order: steam, pour.
serve()is deleted fromLatte. What prints?
It printspourandorder: pour.. The search fromLattenow ends inDrinkforserve().- A third line prints
d.art(). Compile or not?
It does not compile..Drinkdeclares noart(). Dispatch never gets a chance, because the name check comes first.
Upcast, then dispatch
- A
Drinkvariable points at aLatteobject. The variable and the object keep different types. - Compile time: for
d.serve()the compiler checks thatDrinkdeclaresserve(). It does. - Run time: Java asks the object. A
Latteoverridesserve(), so that body runs. Lattedoes not overrideorder(), so the inheritedDrinkbody runs, withthisstill theLatte.- Inside the parent's code,
serve()meansthis.serve(). The object decides again.
Now read data and a static method through the same variable. A field is a slot, not a behaviour: both classes declared kind, so the object holds two slots. A static method belongs to the class itself, so there is no object to ask. Read the example, then step through its picture.
Worked example: Fields and static methods
Problem.
main now prints a field, a static method and a field through a cast. What appears?
class Drink {
String kind = "plain";
static String shelf() { return "drink shelf"; }
String serve() { return "pour"; }
String order() { return "order: " + serve(); }
}
class Latte extends Drink {
String kind = "latte";
static String shelf() { return "coffee shelf"; }
@Override
String serve() { return "steam, pour"; }
String art() { return "heart"; }
}
public class Main {
public static void main(String[] args) {
Drink d = new Latte();
System.out.println(d.kind);
System.out.println(d.shelf());
System.out.println(((Latte) d).kind);
}
}What is asked.
Three lines.
Idea.
For fields and static methods, use the type written in front of the dot.
d.kind: the static type ofdisDrink, so theDrinkslot holds the answer,plain.d.shelf():shelfisstatic, soDrink.shelf()runs and returnsdrink shelf.((Latte) d).kind: the cast makes the static typeLatte, so the other slot is read,latte.
Answer.
plain, drink shelf, latte
Common mistake.
Applying dispatch to everything after the dot.
Fields and static methods ignore the object
- The object carries two separate fields named
kind: one from each class. - A field is picked at compile time from the static type.
d.kindreadsplain. - A
staticmethod belongs to a class, not to the object. The variable's type picks it. - The cast gives a
Latteview of the same object, so now theLattefield is read.
Method call or field read
Instance method
Drink d = new Latte();
String s = d.serve();Field
Drink d = new Latte();
String s = d.kind;The difference. Parentheses make it a method call.
Instance methods follow the object; fields and static methods follow the written type.
A child static method with the parent's signature does not override anything. It hides the parent's method, and d.shelf() through a Drink variable still runs the parent's body.
4. final and private
Some members are locked, and some are invisible to the child.
which members a subclass may not replace or even see
A bank lets each account type describe itself, but nobody may change the bank's name, and the audit code must use the bank's own secret routine. How do you say "do not replace this" and "this is mine alone"?
final is a seal: the child can see and use the method, but cannot write a new one. private is a closed drawer: the child cannot even see inside, so it may own a drawer with the same label that has nothing to do with yours. The analogy stops at objects: a sealed variable can still point at a box whose contents change.
Why does this change dispatch? Overriding means a child replaces a method it inherits. A private method is not inherited into the child's view, so there is nothing to replace. The parent's own calls to it are settled at compile time.
Three different locks
| Written | Child may see it | Child may replace it |
|---|---|---|
| plain method | yes | yes, by overriding |
final method | yes | no: compile error |
private method | no | it can only add its own |
static method | yes | no, it can only hide it |
Worked example: Whose secret?
Problem.
What does this print?
class Account {
private String code() { return "parent code"; }
String audit() { return code(); }
final String bank() { return "North Bank"; }
}
class Savings extends Account {
String code() { return "child code"; }
}
public class Main {
public static void main(String[] args) {
Savings s = new Savings();
System.out.println(s.audit());
System.out.println(s.code());
System.out.println(s.bank());
}
}What is asked.
Three lines.
Idea.
Check whether the method being called is private in the class where the call is written.
s.audit()runs the inheritedAccount.audit().- Inside it,
code()is private inAccount, so it meansAccount.code():parent code. s.code()is a call on aSavings, which declares its owncode():child code.bank()is inherited and sealed:North Bank.
Answer.
parent code, child code, North Bank
Common mistake.
Dispatching code() to the child from inside audit().
The Account program prints parent code, child code, North Bank.
- The word
privateis removed fromAccount.code(). What is the first line now?
It printschild code.. The child now overrides the method, so the call insideaudit()dispatches on theSavingsobject. SavingsaddsString bank() { return "mine"; }. Compile or not?
It does not compile.. Afinalmethod cannot be overridden.maindeclaresAccount s = new Savings();and keeps the same three calls. Compile or not?
It does not compile..s.code()now asksAccountforcode(), which is private there.
Worked example: Using a private value without touching it
Problem.
Clicker calls bump() twice. The step size is private and static. What prints?
class Counter {
private static int step = 5;
int total;
final int bump() {
total = total + step;
return total;
}
}
class Clicker extends Counter {
int twice() {
bump();
return bump();
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Clicker().twice());
}
}What is asked.
The number.
Idea.
An inherited method may use private members of its own class on the child's behalf.
new Clicker()starts withtotalequal to 0.bump()isfinalbut inherited, so the child may call it.- The first call makes
total5 and the second makes it 10. twice()returns the result of the second call.
Answer.
10
Common mistake.
Saying the program fails because Clicker cannot see step. It never names step.
A sealed arrow, an open box
Change the contents
final int[] jar = {3, 4};
jar[0] = 30;Change the arrow
final int[] jar = {3, 4};
jar = new int[2];The difference. An index on the left side of the assignment.
final freezes the variable, not the object it points at.
"final means nothing can change" is false. The final array below accepts a new first element, and the program prints the sum with the new value.
A final array that changes
public class Main {
public static void main(String[] args) {
final int[] jar = {3, 4};
jar[0] = 30;
System.out.println(jar[0] + jar[1]);
}
}5. toString and equals
Printing and comparing an object call methods you can replace.
the two methods every object inherits from Object
You print a coin and want to read Coin(5). You compare two cinema seats with the same row and number and want true. Out of the box Java gives you neither, because it cannot know which fields matter to you.
Every class inherits from Object. Its toString() returns the class name, an @ sign and a hexadecimal number. Its equals(Object) answers true only for the very same object. These are ordinary methods, so you replace them by overriding, and the rules of overriding apply in full.
Why must the header match exactly? println and the library's lists only know Object. They call toString() and equals(Object). A method with another header is invisible to them. Also, an override may not be less visible than the method it replaces, and both of these are public.
Worked example: Print a coin
Problem.
What does this print?
class Coin {
private final int value;
Coin(int v) { value = v; }
@Override
public String toString() { return "Coin(" + value + ")"; }
}
public class Main {
public static void main(String[] args) {
Coin c = new Coin(5);
System.out.println(c);
System.out.println("kept " + c);
}
}What is asked.
Two lines.
Idea.
Both println(c) and "kept " + c turn the object into text by calling toString().
println(c)callsc.toString(), which returnsCoin(5)."kept " + calso callstoString()before joining the texts.
Answer.
Coin(5), then kept Coin(5)
Common mistake.
Writing a void method that prints. toString must return the text.
The Coin program prints Coin(5) and kept Coin(5).
- The word
publicis removed fromtoString. Compile or not?
It does not compile.. Package access is weaker thanpublic, and an override cannot reduce access. - The method is renamed
tostringand@Overrideis removed. What kind of text prints first?
It printsCoin@followed by hexadecimal digits.. Java names are case-sensitive. The inheritedtoString()is still in charge. - The return type becomes
void, with a print inside. Compile or not?
It does not compile.. The signature equalstoString()inObject, butvoidcannot replaceString.
Now equality. Because the parameter is an Object, the body does three things in order: test that the argument is a seat, cast it so the compiler lets you reach the fields, then compare field by field. Text fields need equals, because == compares arrows, and equal text may sit in two different objects.
Worked example: Two seats, one place
Problem.
b is built from a fresh copy of the text C. What are the three lines?
class Seat {
private final String row;
private final int num;
Seat(String row, int num) { this.row = row; this.num = num; }
@Override
public boolean equals(Object o) {
if (!(o instanceof Seat)) return false;
Seat other = (Seat) o;
return num == other.num && row.equals(other.row);
}
}
public class Main {
public static void main(String[] args) {
Seat a = new Seat("C", 7);
Seat b = new Seat(new String("C"), 7);
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(a.equals("C7"));
}
}What is asked.
Three boolean lines.
Idea.
== compares the arrows; this equals compares the contents.
aandbare two objects, soa == bisfalse.- In
a.equals(b)the test passes, the cast givesother, the numbers match androw.equalscompares the letters:true. - The argument
"C7"is aString, so the test fails and the method returnsfalse.
Answer.
false, true, false
Common mistake.
Comparing row == other.row. The two row texts are different objects here.
One surprise to settle before the past questions. Two equal literals (text written directly in the code, in quotes) are stored once and shared. This sharing is called interning, so == happens to be true for them. new String(...) always makes a separate object.
Worked example: One literal or a new object
Problem.
What are the three lines?
public class Main {
public static void main(String[] args) {
String a = "mint";
String b = "mint";
String c = new String("mint");
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(c));
}
}What is asked.
Three boolean lines.
Idea.
Count the string objects, then ask which operator looks at the letters.
aandbcome from the same literal, so both reach one object:a == bistrue.cwas made withnew, a second object:a == cisfalse.equalscompares the letters:true.
Answer.
true, false, true
Common mistake.
Saying == is always false for two string variables, or always safe because it worked with literals.
Identity or contents
==
Seat a = new Seat("C", 7);
Seat b = new Seat("C", 7);
boolean same = a == b;equals
Seat a = new Seat("C", 7);
Seat b = new Seat("C", 7);
boolean same = a.equals(b);The difference. The operator against the method call.
== asks "one object?"; an overridden equals asks "same contents?".
boolean equals(Tag other) looks right but is an overload. As soon as the argument's written type is Object, the inherited identity test runs instead.
The overloaded equals
class Tag {
private final int id;
Tag(int id) { this.id = id; }
public boolean equals(Tag other) { return other != null && id == other.id; }
}
public class Main {
public static void main(String[] args) {
Tag a = new Tag(9);
Tag b = new Tag(9);
Object o = b;
System.out.println(a.equals(b));
System.out.println(a.equals(o));
}
}6. Static type, casts and instanceof
The compiler checks the written type; the running program checks the object.
what a line may call, and when a cast is safe
You are handed a flute, a metal stand and a harp, one at a time. One method must accept all three, so its parameter is written Object. Now you want every instrument to play. The compiler only knows each item is "some object". What may you ask of it?
Think of parcels labelled only "item". The warehouse rules let you do only what every item allows, until you relabel a parcel. Relabelling does not change what is inside; if the label turns out wrong when you open it, you have a problem. The analogy stops here: Java checks the label at the moment you relabel it: the cast itself fails, even if you never use the result.
Why two checks? The compiler cannot know what an Object variable will hold, so it allows only Object methods. A cast is your claim that the object is more specific. The compiler accepts a claim that could be true, and the running program verifies it.
Three outcomes, never mixed
| Line | Result |
|---|---|
item.play() on an Object | compilation error |
((Harp) item).play() on a Flute object | compiles, then throws ClassCastException |
((Playable) item).play() on a Flute object | runs |
Worked example: Guarded cast
Problem.
What does the shelf program print?
interface Playable { String play(); }
class Flute implements Playable {
public String play() { return "toot"; }
}
class Harp implements Playable {
public String play() { return "pluck"; }
}
class Stand { }
public class Main {
static String sound(Object item) {
if (!(item instanceof Playable)) {
return "silent";
}
return ((Playable) item).play();
}
public static void main(String[] args) {
System.out.println(sound(new Flute()));
System.out.println(sound(new Stand()));
System.out.println(sound(new Harp()));
}
}What is asked.
Three lines.
Idea.
Test the object, then cast to the type that has the method.
soundreceives aFlute: the test passes, so the cast runs and returnstoot.- A
Standdoes not fit, so the method returnssilentbefore any cast. - A
Harpfits:pluck.
Answer.
toot, silent, pluck
Common mistake.
Casting to Flute, which only the first item fits.
The shelf program prints toot, silent, pluck.
- Both the test and the cast say
Harpinstead ofPlayable. What prints?
It printssilent,silent,pluck.. Only the third object fitsHarp. - The whole
ifblock is removed, leaving only the cast and call. What happens?
It printstootand then throwsClassCastException.. The second cast meets aStand. Output printed before the failure stays printed. - The second call becomes
sound(null). What is the second line?
It printssilent..null instanceofanything isfalse.
One parameter, three objects
- The
Flutepasses the test, so the cast is safe andplay()runs. - A
Standis notPlayable. The cast is never attempted. - The
Harppasses the same test, and its ownplay()body runs.
The same test works on the elements of an Object[] array, because each element is also written as Object. This loop counts the instruments without calling them.
Counting instruments in a mixed array
interface Playable { }
class Flute implements Playable { }
class Harp implements Playable { }
public class Main {
public static void main(String[] args) {
Object[] bag = {new Harp(), "reed", new Flute()};
int found = 0;
for (int i = 0; i < bag.length; i++) {
if (bag[i] instanceof Playable) {
found++;
}
}
System.out.println(found + " of " + bag.length);
}
}
Worked example: The compiler believes you
Problem.
A Van is cast to a Bike. Compile error, or something else?
class Vehicle { }
class Bike extends Vehicle {
String ring() { return "ding"; }
}
class Van extends Vehicle { }
public class Main {
public static void main(String[] args) {
Vehicle v = new Van();
System.out.println("start");
Bike b = (Bike) v;
System.out.println(b.ring());
}
}What is asked.
The output and the ending.
Idea.
A downcast along the family tree compiles; the object is checked at run time.
vis written asVehicle. AVehiclemight be aBike, so the compiler accepts(Bike) v.startis printed.- At run time the object is a
Van, which is not aBike. - The cast throws
ClassCastException; the last line never runs.
Answer.
start, then ClassCastException
Common mistake.
Calling this a compilation error.
One class or the shared interface
Cast to a class
((Flute) item).play();Cast to the interface
((Playable) item).play();The difference. The type inside the parentheses.
In a loop over mixed objects, cast to a type that all of them belong to.
"Any cast compiles" is false. If two classes are unrelated, such as String and Integer, no object can be both, so the compiler rejects the cast.
7. Abstract classes and interfaces
Some types describe work that another class must finish.
types that promise methods, and what happens when two promises meet
Every plant needs care, and care always starts with water. What else a plant needs depends on the plant. A parent class can write the shared part and leave one blank for each child to fill.
An abstract class is a recipe with a missing step. You cannot cook from it, so new is refused. A child that fills every blank is a complete recipe. An interface is a list of promised steps that any class can sign, and a class can sign several. The recipe analogy stops at state: abstract classes can have fields and constructors; interfaces cannot hold per-object fields.
Why the strictness? If an object existed with a blank step, a call to that step would have no body to run. The compiler prevents this at the moment the class is declared, not when the call is made.
Worked example: Parent calls the blank
Problem.
What does this print?
abstract class Plant {
abstract String need();
String care() { return "water; " + need(); }
}
class Cactus extends Plant {
@Override
String need() { return "sun"; }
@Override
String care() { return super.care() + "; rarely"; }
}
public class Main {
public static void main(String[] args) {
Plant p = new Cactus();
System.out.println(p.care());
}
}What is asked.
The line.
Idea.
super.care() runs the parent body, and the call to need() inside it still dispatches.
p.care()dispatches toCactus.care().- It calls
super.care(), the body inPlant. - That body calls
need(), which dispatches toCactus.need():sun. Plant.care()returnswater; sun, and the child appends; rarely.
Answer.
water; sun; rarely
Common mistake.
Stopping after the parent text, or expecting super.care() to use a parent need().
The plant program prints water; sun; rarely.
need()is deleted fromCactus. Compile or not?
It does not compile..Cactuswould be a creatable class with a method that has no body.mainsaysnew Plant(). Compile or not?
It does not compile.. An abstract class cannot be created.care()is deleted fromCactus. What prints?
It printswater; sun.. The inherited body runs, and it still calls the child'sneed().
Interfaces may give a body too. A default method is inherited by implementing classes. A static method is not: it is called only through the interface's own name. What if two interfaces offer the same default?
Worked example: Two defaults, one answer
Problem.
What does this print?
interface Camera {
default String mode() { return "photo"; }
static String maker() { return "LensCo"; }
}
interface Recorder {
default String mode() { return "audio"; }
}
class Gadget implements Camera, Recorder {
@Override
public String mode() {
return Camera.super.mode() + "+" + Recorder.super.mode();
}
}
public class Main {
public static void main(String[] args) {
Camera c = new Gadget();
System.out.println(c.mode());
System.out.println(Camera.maker());
}
}What is asked.
Two lines.
Idea.
The class settles the conflict; Interface.super.method() picks a particular default.
Gadgetoverridesmode(), so the clash is resolved and the class compiles.c.mode()runs the class body, which returnsphoto+audio.Camera.maker()is a static call through the interface name:LensCo.
Answer.
photo+audio, then LensCo
Common mistake.
Expecting the first interface listed to win.
Two defaults, one class must decide
- Both interfaces offer a body for
mode(). Java refuses to guess, soGadgetmust write its own. c.mode()dispatches on the object, so the class's own body runs.Camera.super.mode()names exactly one default and runs it.- The second call picks the other default. The class joins the two results.
Worked example: A class against a default
Problem.
Mango inherits price() twice, and a default calls it. Which price is printed?
interface Priced {
default int price() { return 0; }
default String label() { return "costs " + price(); }
}
class Stock {
public int price() { return 25; }
}
class Mango extends Stock implements Priced { }
public class Main {
public static void main(String[] args) {
Priced p = new Mango();
System.out.println(p.label());
}
}What is asked.
The output.
Idea.
A method inherited from a class beats an equal default from an interface, even for calls made inside the interface.
StockgivesMangoa publicprice()with a body.Pricedoffers a default with the same signature, so the class method wins and there is no error.p.label()has no class version, so the defaultlabel()runs.- Its call
price()dispatches on theMangoand finds the class method, 25.
Answer.
costs 25
Common mistake.
Reporting a conflict, or thinking a default calls its own interface's price().
Default against default, class against default
Two interfaces
class Mango implements Priced, Taxed { }Class and interface
class Mango extends Stock implements Priced { }The difference. One of the two sources is a class.
Equal defaults from unrelated interfaces need your override; a class method wins by itself.
"A class method wins" still demands a legal method. If the superclass method is not public, it cannot stand in for an interface method, and the subclass does not compile.
8. Callbacks and private inner classes
An object can be called back later, and a hidden class can still be used.
passing yourself to another object, and hiding a class behind a public type
A kitchen timer should tell an egg every time a minute passes, so the egg can be turned. The timer was built to work with anything, not only eggs. How can it call back without knowing what an Egg is?
The egg leaves a phone number: a reference to itself, typed as the interface Tick. The timer rings at(minute) on it. The analogy stops at timing: here the call is an ordinary method call, so the timer's loop pauses until the callback returns.
Why an interface? The timer should depend only on what it needs, one method named at. Any class that provides it can be passed in. So can a lambda, a short unnamed method body such as m -> System.out.println(m), which Java turns into an object for an interface with exactly one abstract method.
Worked example: Order of a callback
Problem.
What does the timer program print?
interface Tick { void at(int minute); }
class Timer {
static void run(int minutes, Tick listener) {
for (int m = 1; m <= minutes; m++) {
listener.at(m);
}
System.out.println("timer done");
}
}
class Egg implements Tick {
private int turns;
public void at(int minute) {
turns++;
System.out.println("turn " + turns + " at minute " + minute);
}
}
public class Main {
public static void main(String[] args) {
Timer.run(2, new Egg());
}
}What is asked.
Three lines, in order.
Idea.
Trace nested calls: the inner method finishes before the loop continues.
mainpasses a newEggtoTimer.runwith 2 minutes.- At
m = 1,listener.at(1)runsEgg.at:turnsbecomes 1 and the first line prints. - At
m = 2the same object is called again:turnsbecomes 2. - The loop ends and
runprintstimer done.
Answer.
turn 1 at minute 1, turn 2 at minute 2, timer done
Common mistake.
Printing the callbacks after the whole method has finished, or restarting turns for each call.
The program prints two turn lines and then timer done.
- The line
listener.at(m);is deleted. What prints?
It prints onlytimer done.. Passing a reference does nothing by itself; only a call runs the callback. maininstead saysTimer.run(2, m -> System.out.println("beep " + m));What prints?
It printsbeep 1,beep 2,timer done.. The lambda supplies the single method ofTick.
A callback goes out and comes back
maincreates anEgg. Itsturnsfield starts at 0. It is about to callTimer.run.runreceives a reference to the egg. It only knows that the object is aTick.listener.at(m)calls back into the egg.runis paused underneath.- The loop calls the same object again, so its field keeps counting.
- The last callback has returned. The loop ends and
runprints its own line.
Now the second move. A playlist wants to hand out its songs one by one without showing its array. It declares a private inner class that walks the array, and returns it as a Cursor. Being inner, the walker can read the playlist's private songs.
Worked example: A hidden walker
Problem.
Walk is private. Can main still use it, and what prints?
interface Cursor {
boolean more();
String take();
}
class Playlist {
private final String[] songs = {"dawn", "noon"};
public Cursor cursor() { return new Walk(); }
private class Walk implements Cursor {
private int at;
public boolean more() { return at < songs.length; }
public String take() { return songs[at++]; }
public int position() { return at; }
}
}
public class Main {
public static void main(String[] args) {
Cursor c = new Playlist().cursor();
while (c.more()) {
System.out.println(c.take());
}
}
}What is asked.
The output.
Idea.
main never writes the name Walk; it works through Cursor.
cursor()is a factory method insidePlaylist, so it may writenew Walk().- It returns the object typed as
Cursor, whichmaincan see. more()andtake()are declared inCursor, somainmay call them.- The loop prints
dawn, thennoon, and stops whenatreaches 2.
Answer.
dawn, then noon
Common mistake.
Saying the program cannot compile because the class is private.
Hold it or name it
Through the interface
Cursor c = new Playlist().cursor();By the private name
Playlist.Walk c =
(Playlist.Walk) new Playlist().cursor();The difference. The type written on the left (and in the cast).
A private class may be used through a visible type, never named from outside.
Hiding is by visible type. position() is public inside Walk, yet c.position() does not compile in main, because Cursor does not declare it.
Weeks covering this topic
- Week 3: Inheritance, polymorphism, class hierarchy, modifiers
- Week 4: Abstract classes, interfaces, private classes, callbacks, iterators