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();
}
}
以上會即使getMaxNumberOfPeopleThatICanAccommodate()
不Chair
明確定義的工作,Chair
將使用實施從Seat
。所述protected
修飾符允許子類調用(或覆蓋)的方法,並且還允許類從同一個包調用的方法:
package com.example.furniture;
public class Bed {
public boolean canFitMorePeopleThanThis(Seat seat) {
return peopleICanFit() > seat.getMaxNumberOfPeopleThatICanAccommodate();
}
private int peopleICanFit() {
return 2;
}
}
並且延伸至與受保護的方法中的一個類可以覆蓋該方法太:
package com.example.furniture;
public class ReallySmallChair extends Seat {
public boolean willBreakIfNumberOfPeopleSittingExceeds(int numberOfPeople) {
return numberOfPeople > getMaxNumberOfPeopleThatICanAccommodate();
}
@Override
protected int getMaxNumberOfPeopleThatICanAccommodate() {
return 1;
}
}
但是如果你試圖從外部包訪問受保護的方法,它不會工作:
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;
}
}
你會得到一個編譯器嘗試訪問seat.get...
或chair.get...
方法時出錯。
如果您在不同的包中有Seat的子類,那麼您仍然可以訪問受保護的方法,因爲它滿足兩個條件之一(一個子類或同一個包中的另一個類),但只有它自己的方法:
package com.example.room;
public class RecreationalVehicle extends Seat {
public boolean canAccommodate(int numberOfPeople) {
return numberOfPeople <= getMaxNumberOfPeopleThatICanAccommodate();
}
}
這工作,因爲getMaxNumberOfPeopleThatICanAccommodate()
是屬於到RecreationalVehicle
(它的一個子類)的方法。如果試圖從一個Seat
變量訪問它,它不會允許它,因爲RecreationalVehicle
不允許觸碰另一實例的保護方法,因爲它不是在同一個包:
package com.example.room;
public class RecreationalVehicle extends Seat {
Seat seat = new Seat();
public void foo() {
seat.getMaxNumberOfPeopleThatICanAccommodate();
}
}
會導致編譯器錯誤。
第一個代碼示例不是一種方法。它在Java中稱爲'constructor'。這很清楚。他可以用我的一個構造函數替換他的構造函數,一切都可以正常工作。 – 2014-09-13 08:46:38
'方法1()'在一個名爲'Out'的類中不是構造函數 – ataulm 2014-09-13 08:47:24
'public Out()'=一個公共構造函數; 'method1()'=方法調用;我認爲一切都很清楚。他可以直接調用'method1',因爲它是從Main繼承的受保護的方法。 – 2014-09-13 08:49:29