Packages and Access Modifiers

Who may see a member, within and across packages.

4 lessons · 9 past questions · 45 marks in the papers collected here

Open the interactive lessons →Packages and Access Modifiers past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Packages, imports and full names
  2. The four access levels
  3. Protected across packages
  4. The static type and access

1. Packages, imports and full names

Two classes may share a short name if they live in different packages.

how a class gets a full name and how a file refers to it

A cinema app has a class called Pass. A railway app also has a class called Pass. One day you join the two apps. Which Pass does new Pass() mean?

Think of two people called Meera in one college. The first name is not enough, so you add the family name. For classes, the package plays that part. The analogy stops here: Java never guesses from context which one you meant.

Why this works. Each source file may start with a package line. From then on, the class's real name includes the package. Two real names differ, so both classes can exist in one program. By convention the file sits in a folder with the same name as the package, and javac -d writes the .class files into matching folders.

Full name and simple name

With package rail; at the top, class Pass has the fully qualified name rail.Pass. Its simple name is Pass. A file with no package line puts its classes in the unnamed package, which no named package can import from.

Below are three files. The line // File: shows where each one is saved.

Two classes called Pass

// File: cinema/Pass.java
package cinema;

public class Pass {
    public String show() { return "film at 7"; }
}
// File: rail/Pass.java
package rail;

public class Pass {
    public String show() { return "train at 9"; }
}
// File: Main.java
public class Main {
    public static void main(String[] args) {
        cinema.Pass a = new cinema.Pass();
        rail.Pass b = new rail.Pass();
        System.out.println(a.show());
        System.out.println(b.show());
        System.out.println(a.getClass().getName());
    }
}

Writing full names everywhere is tiring. An import is a line above the classes that says: when this file writes the short name, it means that full name. A single-class import names one class (import rail.Pass;). A * import offers every class of one package (import rail.*;). Neither one copies any code.

When a file writes a short name, the compiler searches in a fixed order. Step through it.

Screen and Pass

// File: cinema/Pass.java
package cinema;

public class Pass {
    public String show() { return "film at 7"; }
}
// File: cinema/Screen.java
package cinema;

public class Screen {
    public String show() { return "screen 2"; }
}
// File: rail/Pass.java
package rail;

public class Pass {
    public String show() { return "train at 9"; }
}
// File: Main.java
import cinema.*;
import rail.Pass;

public class Main {
    public static void main(String[] args) {
        Screen s = new Screen();
        Pass p = new Pass();
        System.out.println(s.show());
        System.out.println(p.show());
    }
}

Where javac finds a short name

  1. Main writes the short name Screen. The compiler must turn it into one full name.
  2. First it reads the imports that name one class. rail.Pass is not a Screen.
  3. Next it looks in the file's own package. Main has no Screen there.
  4. Last come the * imports. cinema.* supplies Screen.
  5. For Pass, the single-name import answers at once. The Pass inside cinema.* is never asked.

Search order for a simple name

OrderWhere the compiler looksIf two match there
1this file's own declarations and single-class importstwo single-class imports of one name are rejected
2other classes of the file's own packagenot possible: names are unique in a package
3* imports, including the automatic java.langthe name is ambiguous when you use it

Worked example: One import, one full name

Problem.

The program must use both passes. One is imported. What does it print?

// File: cinema/Pass.java
package cinema;

public class Pass {
    public String show() { return "film at 7"; }
}
// File: rail/Pass.java
package rail;

public class Pass {
    public String show() { return "train at 9"; }
}
// File: Main.java
import cinema.Pass;

public class Main {
    public static void main(String[] args) {
        Pass a = new Pass();
        rail.Pass b = new rail.Pass();
        System.out.println(a.show() + ", " + b.show());
    }
}

What is asked.

The printed line.

Idea.

An import settles the short name once. The other class must be written in full.

  1. import cinema.Pass; makes Pass mean cinema.Pass in Main.
  2. a is therefore a cinema.Pass.
  3. b is written as rail.Pass, a full name, so no import is involved.
  4. The two show() texts are joined with a comma.

Answer.

film at 7, train at 9

Common mistake.

Adding import rail.Pass; too. Two single-class imports cannot claim one short name.

What if

In the Pass program with one import, Pass means cinema.Pass and rail.Pass is written in full.

  • A second line import rail.Pass; is added under the first. Does it compile?
    It does not compile.. The two single-class imports collide on the simple name Pass. javac rejects the second import line, and it also calls the later use of Pass ambiguous.
  • The import becomes import cinema.*; and a line import rail.*; is added. Which line is now rejected?
    The line that uses the short name Pass does not compile.. Two * imports may both be written. The clash is reported only where the simple name is used, as ambiguous.
  • The import line is deleted and a is declared as cinema.Pass a = new cinema.Pass();. What happens?
    It compiles and prints the same line, film at 7, train at 9.. Both classes are now written in full, so no short name needs to be searched.

Worked example: Your own package against a star

Problem.

desk.Main imports rail.*. Both desk and rail have a Pass. What prints?

// File: rail/Pass.java
package rail;

public class Pass {
    public String show() { return "train at 9"; }
}
// File: desk/Pass.java
package desk;

public class Pass {
    public String show() { return "desk visitor"; }
}
// File: desk/Main.java
package desk;

import rail.*;

public class Main {
    public static void main(String[] args) {
        System.out.println(new Pass().show());
        System.out.println(new rail.Pass().show());
    }
}

What is asked.

Two lines.

Idea.

The file's own package is searched before any * import.

  1. Main is in package desk, as its first line says.
  2. new Pass() looks for a single-class import: there is none.
  3. Next comes the own package, and desk.Pass exists. The search stops.
  4. new rail.Pass() is a full name, so it needs no search.

Answer.

desk visitor, then train at 9

Common mistake.

Reporting an ambiguity. The star import never competes with the own package.

One name or a whole shelf

Single-class import

Claims one short name firmly.

import cinema.Pass;
import rail.*;

Two star imports

Offers two shelves, with no preference.

import cinema.*;
import rail.*;

The difference. Whether one line names the class itself.

With a single-class import, Pass is settled. With two stars only, using Pass is ambiguous.

When this breaks

"A star import brings in everything below that name" is false. import farm.*; offers the classes of package farm only. A package farm.tools is a separate package, so a class farm.tools.Rake still needs its own import or its full name.

2. The four access levels

Each member carries a rule about who may mention it.

which classes may use a field, method or class

A bank Locker stores a secret pin, a shelf tag, a floor number and an owner name. The pin is nobody's business. The tag is for bank staff. The owner's name may be printed anywhere. How does one class say all of that?

Picture four doors in a building: your own room, your office floor, the family branch offices, and the street. Each wider door admits everyone from the narrower one. The picture stops at the family door, which has an extra condition that the next section explains.

Why have levels at all? Whatever other code can touch, you can no longer change freely. A narrow level keeps the freedom to rewrite a class without breaking others. The compiler enforces this, so a forbidden line never runs.

The access table

WrittenSame classSame packageSubclass in another packageOther class in another package
privateyesnonono
(no modifier)yesyesnono
protectedyesyesyes, with a conditionno
publicyesyesyesyes
The four levels

From closed to open: private, package-private (no modifier written), protected, public. protected includes everything package-private allows.

Four callers of one field

// File: bank/Vault.java
package bank;

public class Vault { public int gold = 3; }
// File: bank/Guard.java
package bank;

public class Guard { public int look() { return new Vault().gold; } }
// File: town/SafeVault.java
package town;

public class SafeVault extends bank.Vault { public int own() { return this.gold; } }
// File: town/Tourist.java
package town;

public class Tourist { public int peek() { return new bank.Vault().gold; } }

One field, four callers, four levels

  1. private stops at the class that declares the field.
  2. No modifier opens the field to the whole package bank, and nothing outside it.
  3. protected adds subclasses in other packages, using the field of their own objects.
  4. public opens the field to every class that can see Vault.

A locker and its clerk

// File: bank/Locker.java
package bank;

public class Locker {
    private int pin;
    String tag;
    protected int floor;
    public String owner;

    public Locker(int pin, String tag, int floor, String owner) {
        this.pin = pin;
        this.tag = tag;
        this.floor = floor;
        this.owner = owner;
    }

    public boolean samePin(Locker other) {
        return pin == other.pin;
    }
}
// File: bank/Clerk.java
package bank;

public class Clerk {
    public String read(Locker k) {
        return k.tag + " / " + k.floor + " / " + k.owner;
    }
}
// File: Main.java
import bank.Clerk;
import bank.Locker;

public class Main {
    public static void main(String[] args) {
        Locker a = new Locker(41, "L1", 2, "Ira");
        Locker b = new Locker(41, "L2", 3, "Om");
        System.out.println(a.samePin(b));
        System.out.println(new Clerk().read(b));
    }
}

Worked example: Private belongs to the class

Problem.

samePin reads other.pin, a private field of a different object. What does the program print?

// File: bank/Locker.java
package bank;

public class Locker {
    private int pin;
    String tag;
    protected int floor;
    public String owner;

    public Locker(int pin, String tag, int floor, String owner) {
        this.pin = pin;
        this.tag = tag;
        this.floor = floor;
        this.owner = owner;
    }

    public boolean samePin(Locker other) {
        return pin == other.pin;
    }
}
// File: bank/Clerk.java
package bank;

public class Clerk {
    public String read(Locker k) {
        return k.tag + " / " + k.floor + " / " + k.owner;
    }
}
// File: Main.java
import bank.Clerk;
import bank.Locker;

public class Main {
    public static void main(String[] args) {
        Locker a = new Locker(41, "L1", 2, "Ira");
        Locker b = new Locker(41, "L2", 3, "Om");
        System.out.println(a.samePin(b));
        System.out.println(new Clerk().read(b));
    }
}

What is asked.

Two lines.

Idea.

private is a limit on the class that writes the line, not on the object.

  1. a.samePin(b) runs code written inside Locker.
  2. Inside Locker, other.pin is legal for any Locker object.
  3. Both pins are 41, so the first line is true.
  4. Clerk shares the package, so it may read tag, floor and owner of b.

Answer.

true, then L2 / 3 / Om

Common mistake.

Thinking one object can never see another object's private field.

Worked example: Which lines are rejected

Problem.

Which of the marked lines stop compilation?

// File: bank/Locker.java
package bank;

public class Locker {
    private int pin;
    String tag;
    protected int floor;
    public String owner;

    public Locker(int pin, String tag, int floor, String owner) {
        this.pin = pin;
        this.tag = tag;
        this.floor = floor;
        this.owner = owner;
    }

    public boolean samePin(Locker other) {
        return pin == other.pin;
    }
}
// File: bank/Clerk.java
package bank;

public class Clerk {
    public String read(Locker k) {
        return k.tag + " / " + k.floor + " / " + k.owner;
    }
}
// File: Main.java
import bank.Locker;

public class Main {
    public static void main(String[] args) {
        Locker a = new Locker(41, "L1", 2, "Ira");
        Locker b = new Locker(41, "L2", 3, "Om");
        System.out.println(b.owner); // LINE 1
        System.out.println(b.floor); // LINE 2
        System.out.println(b.tag);   // LINE 3
        System.out.println(b.pin);   // LINE 4
    }
}

What is asked.

The line numbers with errors.

Idea.

Name the caller first, then read one row of the table per field.

  1. The caller is Main: another package, no extends. Only the last column of the table applies.
  2. owner is public: allowed.
  3. floor is protected, and Main is not a subclass: rejected.
  4. tag has no modifier and Main is outside bank: rejected.
  5. pin is private: rejected.

Answer.

LINE 2, LINE 3 and LINE 4

Common mistake.

Allowing the protected field because it sounds more open than no modifier. For an unrelated outsider, both are closed.

What if

Main is outside bank, and only b.owner is accepted.

  • The four reads move into a new method of Clerk, inside package bank. Which lines are still rejected?
    Only the pin line does not compile.. Clerk is a package neighbour, so only private still blocks it.
  • The reads move into a method of Locker itself. How many errors remain?
    None: all four compile.. Inside the declaring class every level is open.
  • tag is changed to public String tag; and Main stays outside. Which lines are rejected now?
    The floor and pin lines do not compile.. Only the modifier of tag changed, so only its line is repaired.

No modifier against protected

No modifier

A subclass in another package gets nothing.

int floor;

protected

A subclass in another package may use it on its own objects.

protected int floor;

The difference. The single word protected.

The two differ only for subclasses outside the package. Inside the package they behave the same.

When this breaks

"I called it with a String, so the String method ran, so I have access to it" can be false. The compiler first throws away every method it may not use, then chooses the best remaining one. A hidden overload can silently lose to a wider visible one.

Worked example: The overload that is not there

Problem.

Mixer has three set methods. The one taking a String has no modifier. What does Main print?

// File: studio/Mixer.java
package studio;

public class Mixer {
    public String set(int level) { return "number"; }
    String set(String preset) { return "preset"; }
    public String set(Object any) { return "anything"; }
}
// File: Main.java
import studio.Mixer;

public class Main {
    public static void main(String[] args) {
        Mixer m = new Mixer();
        System.out.println(m.set(4));
        System.out.println(m.set("loud"));
    }
}

What is asked.

Two lines.

Idea.

Overload choice looks only at methods the caller may use.

  1. m.set(4) fits the public int method: number.
  2. For m.set("loud"), the String method is package-private in studio, and Main is outside.
  3. It is removed from the list of candidates.
  4. The public Object method still accepts a String, so it runs.

Answer.

number, then anything

Common mistake.

Predicting a compilation error, or preset. The call is legal because another method accepts the value.

3. Protected across packages

Being a child is not enough: the line must be written in the child and aimed at the child's own kind.

when a subclass, or anyone else, may use a protected member from another package

Plant, in package garden, offers a protected method water(). A team in package yard writes Rose extends Plant. Inside Rose, which of these may call the method, and may a visitor to the yard call it too?

Think of a family recipe. A daughter may cook it in her own kitchen. She may not walk into her cousin's kitchen and cook there, and a guest who visits her may not either. The picture stops here: Java judges the written type of a variable, not who really owns the kitchen.

Why the condition? protected exists so that a child class can build on its parent. If Rose could use the method on any Plant, then by declaring a subclass anyone could reach into every plant, including unrelated kinds such as a Tulip. So Java asks for proof that the object is one of the child's own.

The protected rule

For code in class S, in a different package from the declaring class: the line q.m() is legal only if S is a subclass of the declaring class and the written type of q is S or a subclass of S. super.m() and a plain m() inside S are legal too.

Rose uses what it inherits

// File: garden/Plant.java
package garden;

public class Plant {
    protected int height = 10;
    protected String water() { return "water " + height; }
}
// File: yard/Rose.java
package yard;

import garden.Plant;

public class Rose extends Plant {
    public String care() {
        height = height + 5;
        return water() + ", " + this.water() + ", " + super.water();
    }
    public String help(Rose other) {
        return other.water();
    }
}
// File: Main.java
import yard.Rose;

public class Main {
    public static void main(String[] args) {
        Rose r = new Rose();
        System.out.println(r.care());
        System.out.println(r.help(new Rose()));
    }
}

Worked example: Three spellings, one method

Problem.

What do care() and help(...) print?

// File: garden/Plant.java
package garden;

public class Plant {
    protected int height = 10;
    protected String water() { return "water " + height; }
}
// File: yard/Rose.java
package yard;

import garden.Plant;

public class Rose extends Plant {
    public String care() {
        height = height + 5;
        return water() + ", " + this.water() + ", " + super.water();
    }
    public String help(Rose other) {
        return other.water();
    }
}
// File: Main.java
import yard.Rose;

public class Main {
    public static void main(String[] args) {
        Rose r = new Rose();
        System.out.println(r.care());
        System.out.println(r.help(new Rose()));
    }
}

What is asked.

Two lines.

Idea.

All the calls are inside Rose on Rose objects, so all are legal; then trace the field.

  1. new Rose() starts with height equal to 10.
  2. care() adds 5 to this object's height, giving 15.
  3. water(), this.water() and super.water() all run the only version, in Plant.
  4. help(new Rose()) asks a fresh rose, whose height is still 10.

Answer.

water 15, water 15, water 15, then water 10

Common mistake.

Carrying the 15 over to the second object.

Who may call a protected method?

  1. Inside Rose, super.water() reaches the protected method of the object's own parent part.
  2. Another object is fine when its written type is Rose or a subclass of Rose.
  3. Through a Plant variable the object might be any plant, so Rose is refused.
  4. Visitor is no subclass of Plant. A Rose variable does not help it.
  5. Keeper shares the package of Plant, where water() is declared, so it is allowed.

Worked example: Four references, inside Rose

Problem.

Climber extends Rose. Tulip extends Plant. Which marked lines are rejected?

// File: garden/Plant.java
package garden;

public class Plant {
    protected String water() { return "water"; }
}
// File: yard/Rose.java
package yard;

import garden.Plant;

public class Rose extends Plant {
    public void check(Plant p, Rose r, Climber c, Tulip t) {
        p.water(); // LINE 1
        r.water(); // LINE 2
        c.water(); // LINE 3
        t.water(); // LINE 4
    }
}
// File: yard/Climber.java
package yard;

public class Climber extends Rose { }
// File: yard/Tulip.java
package yard;

import garden.Plant;

public class Tulip extends Plant { }
// File: Main.java
public class Main {
    public static void main(String[] args) { }
}

What is asked.

The line numbers with errors.

Idea.

For each qualifier, ask whether its written type is Rose or lower.

  1. The code is written in Rose, in package yard; water() is declared in garden.
  2. p is a Plant: higher than Rose, so rejected.
  3. r is a Rose: allowed.
  4. c is a Climber, below Rose: allowed.
  5. t is a Tulip, a sibling and not below Rose: rejected.

Answer.

LINE 1 and LINE 4

Common mistake.

Allowing the sibling because it is also a subclass of Plant.

What if

Inside Rose, the Plant and Tulip references are rejected; the Rose and Climber references are accepted.

  • The same four lines are written inside Climber instead. Which lines are rejected now?
    The Plant, Rose and Tulip lines do not compile; only the Climber line is accepted.. The bar is now Climber or lower, and a Rose is higher than that.
  • Rose.java is moved to package garden (and the other files import it from there). Which lines are rejected?
    None: all four compile.. Rose now shares the declaring package, so ordinary package access applies and no condition remains.
  • Rose gets its own method protected String water() { return "rose"; }, and the Plant line stays. Is the Plant line accepted now?
    It still does not compile.. The compiler looks up water() in Plant, the written type of p. The child's version changes nothing there.

Worked example: A neighbour of the parent

Problem.

Keeper is in garden. Rose is in yard and declares nothing. Does Keeper compile, and what prints?

// File: garden/Plant.java
package garden;

public class Plant {
    protected String water() { return "plant watered"; }
}
// File: garden/Keeper.java
package garden;

import yard.Rose;

public class Keeper {
    public String visit() { return new Rose().water(); }
}
// File: yard/Rose.java
package yard;

import garden.Plant;

public class Rose extends Plant { }
// File: Main.java
import garden.Keeper;

public class Main {
    public static void main(String[] args) {
        System.out.println(new Keeper().visit());
    }
}

What is asked.

The output.

Idea.

The relevant package is the one where the method is declared.

  1. new Rose().water() names a method that Rose only inherits.
  2. The declaration is in Plant, package garden.
  3. Keeper is also in garden, so package access applies.
  4. The call is legal and runs the Plant body.

Answer.

plant watered

Common mistake.

Rejecting the call because the object's class lives in another package.

Same call, different reference

Own type

Written inside Rose: accepted.

String f(Rose x) { return x.water(); }

Parent type

Written inside Rose: rejected.

String f(Plant x) { return x.water(); }

The difference. The written type of the parameter.

Outside the package, the qualifier must be the writing class or lower.

When this breaks

"The qualifier must be my own type" is a rule for instance members. For a protected static method, any subclass may write Plant.kind(), because there is no object whose kind could matter.

4. The static type and access

The compiler asks the variable's class for permission; the program asks the object for the body.

how access is checked when a parent variable holds a child object

A Parcel from package post keeps weigh() protected. A Crate from package depot extends it and makes weigh() public. In Main, one variable written as Parcel and one written as Crate point at the same crate. Which of them may ask for the weight?

Think of one building with two entrances. The front entrance lets visitors into more rooms than the side entrance. The building is the same; the entrance you use decides what you may ask for. Here the entrance is the type written on the variable.

Why not look at the object? The compiler works before the program runs, so it cannot know which object a variable will hold. It can only promise safety from what is written. After that promise, the running program picks the most specific body for the actual object.

Two questions, in order

1. Compile time: does the static type declare or inherit this member, and may this line use it at that level? 2. Run time: for an overridable method, which body does the object's class supply?

Parcel and Crate

// File: post/Parcel.java
package post;

public class Parcel {
    public String kind() { return "parcel"; }
    protected int weigh() { return 2; }
    private String seal() { return "wax"; }
    public String slip() { return kind() + " " + weigh() + " " + seal(); }
}
// File: depot/Crate.java
package depot;

import post.Parcel;

public class Crate extends Parcel {
    @Override
    public String kind() { return "crate"; }
    @Override
    public int weigh() { return 30; }
    public String seal() { return "tape"; }
}
// File: Main.java
import depot.Crate;
import post.Parcel;

public class Main {
    public static void main(String[] args) {
        Parcel p = new Crate();
        Crate c = (Crate) p;
        System.out.println(p.kind());
        System.out.println(p.slip());
        System.out.println(c.weigh() + " " + c.seal());
    }
}

Worked example: Same object, two views

Problem.

What does the program print?

// File: post/Parcel.java
package post;

public class Parcel {
    public String kind() { return "parcel"; }
    protected int weigh() { return 2; }
    private String seal() { return "wax"; }
    public String slip() { return kind() + " " + weigh() + " " + seal(); }
}
// File: depot/Crate.java
package depot;

import post.Parcel;

public class Crate extends Parcel {
    @Override
    public String kind() { return "crate"; }
    @Override
    public int weigh() { return 30; }
    public String seal() { return "tape"; }
}
// File: Main.java
import depot.Crate;
import post.Parcel;

public class Main {
    public static void main(String[] args) {
        Parcel p = new Crate();
        Crate c = (Crate) p;
        System.out.println(p.kind());
        System.out.println(p.slip());
        System.out.println(c.weigh() + " " + c.seal());
    }
}

What is asked.

Three lines.

Idea.

Check access through the written type, then run the object's bodies.

  1. p.kind() is public in Parcel; the object is a Crate, so it gives crate.
  2. p.slip() is public and not overridden, so the Parcel body runs on the crate.
  3. Inside it, kind() and weigh() are overridden: crate and 30.
  4. seal() is private in Parcel, so the parent's own method is used: wax.
  5. c is a Crate, whose weigh() and seal() are public: 30 tape.

Answer.

crate, then crate 30 wax, then 30 tape

Common mistake.

Writing tape in the second line. A private method is never replaced by a child method.

The variable decides access, the object decides the body

  1. p is written as Parcel. The object is a Crate, which made weigh public.
  2. For p.kind() the compiler reads the Parcel declaration. It is public, so the call is allowed.
  3. At run time the object decides, so the Crate body runs.
  4. p.weigh() is judged by Parcel: protected, and Main is no subclass. The public Crate version cannot help.
  5. After the cast, c has static type Crate. There weigh() is public, so the same object now answers.

Worked example: Which view is refused

Problem.

b is written as the interface Beeps. Which marked lines are rejected?

// File: metro/Beeps.java
package metro;

public interface Beeps { String beep(); }
// File: metro/Turnstile.java
package metro;

public class Turnstile implements Beeps {
    public String beep() { return "beep"; }
    public String count() { return "7 riders"; }
    String reset() { return "reset"; }
}
// File: Main.java
import metro.Beeps;
import metro.Turnstile;

public class Main {
    public static void main(String[] args) {
        Beeps b = new Turnstile();
        System.out.println(b.beep());                  // LINE 1
        System.out.println(b.count());                 // LINE 2
        System.out.println(((Turnstile) b).count());   // LINE 3
        System.out.println(((Turnstile) b).reset());   // LINE 4
    }
}

What is asked.

The line numbers with errors.

Idea.

For each line, find the type written in front of the dot. Does it declare the method, and may Main use it there?

  1. b.beep(): Beeps declares it, and this interface method is public: accepted.
  2. b.count(): Beeps declares no count, so the line is rejected, although the object has one.
  3. ((Turnstile) b).count(): the cast opens Turnstile, where count is public: accepted.
  4. ((Turnstile) b).reset(): the cast finds reset, but it has no modifier and Main is outside metro: rejected.

Answer.

LINE 2 and LINE 4

Common mistake.

Thinking a cast opens every method. It changes which class is read; the access level written there still applies.

What if

Main is outside package metro. LINE 1 and LINE 3 are accepted; LINE 2 and LINE 4 are not.

  • Beeps also declares String count(); What happens to LINE 2?
    It compiles and prints 7 riders.. The written type now declares the method.
  • reset() in Turnstile is written public. What does LINE 4 print?
    It prints reset.. The cast already finds the method, and now Main may use it.
  • The word public is removed from beep() in Turnstile. What happens?
    Turnstile does not compile.. A method that implements an interface method may not be narrower than public.

Which entrance

Parent view

Rejected from Main.

Parcel x = new Crate();
x.weigh();

Child view

Accepted from Main.

Crate x = new Crate();
x.weigh();

The difference. The type written before the variable name.

The object is identical; permission comes from the static type.

When this breaks

"The object's class picks the body" fails for a package-private method redeclared in another package. The child cannot see the parent's method, so it does not override it. The parent's own code keeps calling the parent's version.

Worked example: A method that was never overridden

Problem.

RedStamp declares a public ink(). The parent's ink() has no modifier. What prints?

// File: post/Stamp.java
package post;

public class Stamp {
    String ink() { return "blue"; }
    public String press() { return ink(); }
}
// File: depot/RedStamp.java
package depot;

import post.Stamp;

public class RedStamp extends Stamp {
    public String ink() { return "red"; }
}
// File: Main.java
import depot.RedStamp;
import post.Stamp;

public class Main {
    public static void main(String[] args) {
        Stamp s = new RedStamp();
        System.out.println(s.press());
        System.out.println(new RedStamp().ink());
    }
}

What is asked.

Two lines.

Idea.

First decide whether the child overrides at all.

  1. Stamp.ink() is package-private in post; RedStamp is in depot.
  2. So RedStamp.ink() is a separate new method.
  3. s.press() runs in Stamp and calls Stamp's ink(): blue.
  4. new RedStamp().ink() is a call on the static type RedStamp: red.

Answer.

blue, then red

Common mistake.

Expecting red twice. Adding @Override to the child method would make javac reject it.

Practise this topic →

Weeks covering this topic

Other Java topics