package com.example.furniture;
public class Seat {
public boolean canAccommodate(int numberOfPeople) {
return numberOfPeople <= getMaxNumberOfPeopleThatICanAccommodate();
}
protected int getMaxNumberOfPeopleThatICanAccommodate() {
return 4;
}
}
package com.example.furniture;
public class Chair extends Seat {
public boolean willBreakIfNumberOfPeopleSittingExceeds(int numberOfPeople) {
return numberOfPeople > getMaxNumberOfPeopleThatICanAccommodate();
}
}
The above would work even though getMaxNumberOfPeopleThatICanAccommodate()
isn't defined explicitly in Chair
, Chair
will use the implementation from Seat
. The protected
modifier allows subclasses to call (or override) the method, and also allows classes from the same package to call the method:
package com.example.furniture;
public class Bed {
public boolean canFitMorePeopleThanThis(Seat seat) {
return peopleICanFit() > seat.getMaxNumberOfPeopleThatICanAccommodate();
}
private int peopleICanFit() {
return 2;
}
}
And classes extending the one with the protected method can override that method too:
package com.example.furniture;
public class ReallySmallChair extends Seat {
public boolean willBreakIfNumberOfPeopleSittingExceeds(int numberOfPeople) {
return numberOfPeople > getMaxNumberOfPeopleThatICanAccommodate();
}
@Override
protected int getMaxNumberOfPeopleThatICanAccommodate() {
return 1;
}
}
But if you try to access the protected method from an external package, it won't work:
package com.example.room;
public class LivingRoom {
Seat seat = new Seat();
Seat chair = new Chair();
public boolean canAccommodate(int numberOfPeople) {
int maxAccommodate = seat.getMaxNumberOfPeopleThatICanAccommodate() +
chair.getMaxNumberOfPeopleThatICanAccommodate();
return numberOfPeople <= maxAccommodate;
}
}
You'll get a compiler error when trying to access either the seat.get...
or chair.get...
methods.
If you had a subclass of Seat in a different package, then you could still access the protected methods because it fulfils one of the two conditions (a subclass, or another class in the same package), but only its own method:
package com.example.room;
public class RecreationalVehicle extends Seat {
public boolean canAccommodate(int numberOfPeople) {
return numberOfPeople <= getMaxNumberOfPeopleThatICanAccommodate();
}
}
That works, because getMaxNumberOfPeopleThatICanAccommodate()
is a method that belongs to RecreationalVehicle
(it's a subclass). If it tried to access it from a Seat
variable, it wouldn't allow it because RecreationalVehicle
isn't allowed to touch another instance's protected methods as it's not in the same package:
package com.example.room;
public class RecreationalVehicle extends Seat {
Seat seat = new Seat();
public void foo() {
seat.getMaxNumberOfPeopleThatICanAccommodate();
}
}
would cause a compiler error.