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