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 하위 클래스가있는 경우 두 조건 중 하나 (동일한 패키지의 하위 클래스 또는 다른 클래스) 중 하나를 충족시키기 때문에 보호 된 메서드에 액세스 할 수 있지만 자체 메서드 만 사용할 수 있습니다 :
getMaxNumberOfPeopleThatICanAccommodate()
이
이
RecreationalVehicle
에 (이 서브 클래스의)에 속하는하는 방법이기 때문에, 작동
package com.example.room;
public class RecreationalVehicle extends Seat {
public boolean canAccommodate(int numberOfPeople) {
return numberOfPeople <= getMaxNumberOfPeopleThatICanAccommodate();
}
}
. 그것은 Seat
변수에서 액세스하려고하면 RecreationalVehicle
은 (는) 동일한 패키지에없는 같은 다른 인스턴스의 보호 방법을 만져 허용되지 않기 때문에, 그것을 허용하지 않을 :
package com.example.room;
public class RecreationalVehicle extends Seat {
Seat seat = new Seat();
public void foo() {
seat.getMaxNumberOfPeopleThatICanAccommodate();
}
}
는 컴파일러 오류가 발생합니다. 당신이 실제로 다른 패키지에서 슈퍼 클래스의 메소드를 호출 할 수처럼
첫 번째 코드 예제는 메서드가 아닙니다. 자바에서는'constructor'이라고합니다. 그리고 그것은 매우 분명합니다. 그는 단지 생성자를 내 생성자 중 하나로 대체 할 수 있으며 모든 것이 잘 작동합니다. –
'Out' 클래스의'method1()'이 생성자가 아닙니다. – ataulm
'public Out()'= public 생성자입니다. 'method1()'= 메소드 호출; 나는 모든 것이 분명하다고 생각한다. Main으로부터 상속받은 보호 된 메소드이기 때문에 그는'method1'를 직접 호출 할 수 있습니다. –