的方法:种植plant(),生长grow()以及收获harvest()。
这个水果接口的源代码如下所示。
代码清单1:接口Fruit 的源代码
public interface Fruit {
// 生长
void grow();
//收获
void harvest();
//种植
void plant();
}
Apple 类是水果类的一种,因此它实现了水果接口所声明的所有方法。另外,由于苹果是多年生植物,因此多出一个treeAge 性质,描述苹果树的树龄。下面是这个苹果类的源代码。
代码清单2:类Apple 的源代码
public class Apple
implements Fruit {
private int treeAge;
//生长
public void grow() {
log("Apple is growing...");
}
// 收获
public void harvest() {
log("Apple has been harvested.");
}
//种植
public void plant() {
log("Apple has been planted.");
}
// 辅助方法
public static void log(String msg) {
System.out.println(msg);
}
//树龄的取值方法
public int getTreeAge() {
return treeAge;
}
// 树龄的赋值方法
public void setTreeAge(int treeAge) {
this.treeAge = treeAge;
}
}
同样,Grape 类是水果类的一种,也实现了Fruit 接口所声明的所有的方法。但由于葡萄分有籽和无籽两种,因此,比通常的水果多出一个seedless 性质,葡萄类的
源代码如下所示。可以看出,Grape 类同样实现了水果接口,从而是水果类型的一种子类型。
代码清单3:类Grape 的源代码
public class Grape
implements Fruit {
private boolean seedless;
//生长
public void grow() {
log("Grape is growing...");
}
//收获
public void harvest() {
log("Grape has been harvested.");
}
//种植
public void plant() {
log("Grape has been planted.");
}
//辅助方法
public static void log(String msg) {
System.out.println(msg);
}
// 有无籽的取值方法
public boolean getSeedless() {
return seedless;
}
//有无籽的赋值方法
public void setSeedless(boolean seedless) {
this.seedless = seedless;
}
}
Strawberry 类实现了Fruit 接口,因此,也是水果类型的子类型,其源代码如下所示。
代码清单4:类Strawberry 的源代码
public class Strawberry
implements Fruit {
//生长
public void grow() {
log("Strawberry is growing...");
}
//收获
public void harvest() {
log("Strawberry has been harvested.");
}<