179页的:
/**
* Exercise 14: (1) In Car.java add a service( ) method to Engine
* and call this method in main( ).
*/
package reusing;
class Engine {
public void start() {}
public void rev() {}
public void stop() {}
//按照作业要求加上一个service()方法, service()可以为public或者默认的package access,
//但是不能声明为private,
//如果为private, 则main将看不见service, 从而无法调用.
public void service(){
System.out.println("Service is called.");
}
}
class Wheel {
public void inflate(int psi) {}
}
class Window {
public void rollup() {}
public void rolldown() {}
}
class Door {
public Window window = new Window();
public void open() {}
public void close() {}
}
public class P179Car {
//engine将能为外部程序调用, 以便进行检查
public Engine engine = new Engine();
public Wheel[] wheel = new Wheel[4];
public Door
left = new Door(),
right = new Door(); // 2-door
public P179Car() {
for(int i = 0; i < 4; i++)
wheel[i] = new Wheel();
}
public static void main(String[] args) {
P179Car car = new P179Car();
car.left.window.rollup();
car.wheel[0].inflate(72);
//在main中调用service
car.engine.service();
}
}
180页的excercise 15. 友情提醒: 要做对这题, 要对package access, public, protected等术语有一个基本的了解.
1. 外部package中的类:
/**
* 这个类是配合reusing package中的P180E15类使用的
*/
package foreign;
public class P180Prot {
//构造函数必须声明为public, 以便P180E15使用
public P180Prot(){
System.out.println("Constructor of P180Prot.");
}
protected void protMethod(){
System.out.println("我是class P180Prot中的方法protMethod(), 访问权限为protected.");
}
}
2.调用外部类的protected方法
package reusing;
import foreign.P180Prot;
public class P180E15 extends P180Prot{
P180E15(){
super();
}
public static void main(String[] args) {
//如果P180E15不extends P180Prot, 则无法访问其proMethod().
P180E15 x=new P180E15();
//要成功调用, 构造函数P180Prot()必须声明为public, 而不能为protected.
x.protMethod();
}
}