Who may see a member, within and across packages.
Open the interactive lessons →Packages and Access Modifiers past questions
Contents
- Packages, imports and full names
- The four access levels
- Protected across packages
- 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.
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
Mainwrites the short nameScreen. The compiler must turn it into one full name.- First it reads the imports that name one class.
rail.Passis not aScreen. - Next it looks in the file's own package.
Mainhas noScreenthere. - Last come the
*imports.cinema.*suppliesScreen. - For
Pass, the single-name import answers at once. ThePassinsidecinema.*is never asked.
Search order for a simple name
| Order | Where the compiler looks | If two match there |
|---|---|---|
| 1 | this file's own declarations and single-class imports | two single-class imports of one name are rejected |
| 2 | other classes of the file's own package | not possible: names are unique in a package |
| 3 | * imports, including the automatic java.lang | the 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.
import cinema.Pass;makesPassmeancinema.PassinMain.ais therefore acinema.Pass.bis written asrail.Pass, a full name, so no import is involved.- 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.
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 namePass.javacrejects the second import line, and it also calls the later use ofPassambiguous. - The import becomes
import cinema.*;and a lineimport rail.*;is added. Which line is now rejected?
The line that uses the short namePassdoes 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
ais declared ascinema.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.
Mainis in packagedesk, as its first line says.new Pass()looks for a single-class import: there is none.- Next comes the own package, and
desk.Passexists. The search stops. 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.
"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
| Written | Same class | Same package | Subclass in another package | Other class in another package |
|---|---|---|---|---|
private | yes | no | no | no |
| (no modifier) | yes | yes | no | no |
protected | yes | yes | yes, with a condition | no |
public | yes | yes | yes | yes |
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
privatestops at the class that declares the field.- No modifier opens the field to the whole package
bank, and nothing outside it. protectedadds subclasses in other packages, using the field of their own objects.publicopens the field to every class that can seeVault.
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.
a.samePin(b)runs code written insideLocker.- Inside
Locker,other.pinis legal for anyLockerobject. - Both pins are 41, so the first line is
true. Clerkshares the package, so it may readtag,floorandownerofb.
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.
- The caller is
Main: another package, noextends. Only the last column of the table applies. ownerispublic: allowed.floorisprotected, andMainis not a subclass: rejected.taghas no modifier andMainis outsidebank: rejected.pinisprivate: 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.
Main is outside bank, and only b.owner is accepted.
- The four reads move into a new method of
Clerk, inside packagebank. Which lines are still rejected?
Only thepinline does not compile..Clerkis a package neighbour, so onlyprivatestill blocks it. - The reads move into a method of
Lockeritself. How many errors remain?
None: all four compile.. Inside the declaring class every level is open. tagis changed topublic String tag;andMainstays outside. Which lines are rejected now?
Thefloorandpinlines do not compile.. Only the modifier oftagchanged, 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.
"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.
m.set(4)fits the publicintmethod:number.- For
m.set("loud"), theStringmethod is package-private instudio, andMainis outside. - It is removed from the list of candidates.
- The public
Objectmethod still accepts aString, 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.
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.
new Rose()starts withheightequal to 10.care()adds 5 to this object'sheight, giving 15.water(),this.water()andsuper.water()all run the only version, inPlant.help(new Rose())asks a fresh rose, whoseheightis 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?
- Inside
Rose,super.water()reaches the protected method of the object's own parent part. - Another object is fine when its written type is
Roseor a subclass ofRose. - Through a
Plantvariable the object might be any plant, soRoseis refused. Visitoris no subclass ofPlant. ARosevariable does not help it.Keepershares the package ofPlant, wherewater()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.
- The code is written in
Rose, in packageyard;water()is declared ingarden. pis aPlant: higher thanRose, so rejected.ris aRose: allowed.cis aClimber, belowRose: allowed.tis aTulip, a sibling and not belowRose: rejected.
Answer.
LINE 1 and LINE 4
Common mistake.
Allowing the sibling because it is also a subclass of Plant.
Inside Rose, the Plant and Tulip references are rejected; the Rose and Climber references are accepted.
- The same four lines are written inside
Climberinstead. Which lines are rejected now?
ThePlant,RoseandTuliplines do not compile; only theClimberline is accepted.. The bar is nowClimberor lower, and aRoseis higher than that. Rose.javais moved to packagegarden(and the other files import it from there). Which lines are rejected?
None: all four compile..Rosenow shares the declaring package, so ordinary package access applies and no condition remains.Rosegets its own methodprotected String water() { return "rose"; }, and thePlantline stays. Is thePlantline accepted now?
It still does not compile.. The compiler looks upwater()inPlant, the written type ofp. 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.
new Rose().water()names a method thatRoseonly inherits.- The declaration is in
Plant, packagegarden. Keeperis also ingarden, so package access applies.- The call is legal and runs the
Plantbody.
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.
"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.
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.
p.kind()is public inParcel; the object is aCrate, so it givescrate.p.slip()is public and not overridden, so theParcelbody runs on the crate.- Inside it,
kind()andweigh()are overridden:crateand30. seal()is private inParcel, so the parent's own method is used:wax.cis aCrate, whoseweigh()andseal()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
pis written asParcel. The object is aCrate, which madeweighpublic.- For
p.kind()the compiler reads theParceldeclaration. It ispublic, so the call is allowed. - At run time the object decides, so the
Cratebody runs. p.weigh()is judged byParcel: protected, andMainis no subclass. The publicCrateversion cannot help.- After the cast,
chas static typeCrate. Thereweigh()ispublic, 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?
b.beep():Beepsdeclares it, and this interface method is public: accepted.b.count():Beepsdeclares nocount, so the line is rejected, although the object has one.((Turnstile) b).count(): the cast opensTurnstile, wherecountispublic: accepted.((Turnstile) b).reset(): the cast findsreset, but it has no modifier andMainis outsidemetro: 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.
Main is outside package metro. LINE 1 and LINE 3 are accepted; LINE 2 and LINE 4 are not.
Beepsalso declaresString count();What happens toLINE 2?
It compiles and prints7 riders.. The written type now declares the method.reset()inTurnstileis writtenpublic. What doesLINE 4print?
It printsreset.. The cast already finds the method, and nowMainmay use it.- The word
publicis removed frombeep()inTurnstile. What happens?Turnstiledoes not compile.. A method that implements an interface method may not be narrower thanpublic.
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.
"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.
Stamp.ink()is package-private inpost;RedStampis indepot.- So
RedStamp.ink()is a separate new method. s.press()runs inStampand callsStamp'sink():blue.new RedStamp().ink()is a call on the static typeRedStamp:red.
Answer.
blue, then red
Common mistake.
Expecting red twice. Adding @Override to the child method would make javac reject it.