1. 实现类的复用通常有两种方式
2. 一个特殊的方法toString()
3. 父类方法的定义要求
4. 基类初始化
5. 复用的第三种方式: 代理
package net.mindview.reusing;
public class SpaceShipControls {
//velocity 速度
void up(int velocity){}
void down(int velocity){}
void left(int velocity){}
void right(int velocity){}
void forward(int velocity){}
void back(int velocity){}
void turboBoost(int velocity){} //发动
}
package net.mindview.reusing;
public class SpaceShipControls {
//velocity 速度
void up(int velocity){}
void down(int velocity){}
void left(int velocity){}
void right(int velocity){}
void forward(int velocity){}
void back(int velocity){}
void turboBoost(int velocity){} //发动
}
6. 如何选择组合和继承
package net.mindview.reusing;
class Engine {
public void start(){}
public void rev(){}
public void stop(){}
}
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 Car {
public Engine engine = new Engine();
public Wheel[] wheels = new Wheel[4];
public Door left = new Door(),right = new Door();
public Car(){
for(int i=0;i<4; i++){
wheels[i] = new Wheel();
}
}
public static void main(String[] args) {
Car car = new Car();
car.left.window.rollup();
car.wheels[0].inflate(72);
}
}
package net.mindview.reusing;
/**
* 乐器
*/
class Instrument {
public void play(){}
//用乐器弹奏曲调
static void tune(Instrument i){
i.play();
}
}
//乐器的一种
public class Wind extends Instrument{
public static void main(String[] args) {
Wind wind = new Wind();
//使用wind弹奏曲调
Instrument.tune(wind);
}
}
7.final关键字
package net.mindview.reusing;
class Poppet {
private int i;
Poppet(int i){
this.i = i;
}
}
public class BlankFinal {
//定义的时候赋初始值
private final int i = 0;
//空白final
private final int j;
//空白final引用
private final Poppet p;
public BlankFinal(){
j = 1;
p = new Poppet(1);
}
public BlankFinal(int x){
j = x;
p = new Poppet(x);
}
public static void main(String[] args) {
new BlankFinal();
new BlankFinal(4);
}
}
package net.mindview.reusing;
class Gizmo{
public void spin() {}
}
//final作用于方法参数
public class FinalArguments {
//final作用于对象类型的方法参数
void with(final Gizmo g) {
//在这里不可以对传递过来个g重新指向新的引用
//g = new Gizmo();
}
void without(Gizmo g){
g = new Gizmo();
g.spin();
}
//final作用于基本类型的方法参数
void f(final int i) {
//在这里不可以对i重新赋值
//i++;
}
int g(final int i) {
return i+1;
}
public static void main(String[] args) {
FinalArguments bf = new FinalArguments();
bf.with(null);
bf.without(null);
}
}
忠告:再设计类的时候, 将方法定义为final的,应该说是明智的。你可能会觉得,没人想要覆盖你的方法,但预见类是如何被复用是很困难的, 特别是对于一个通用类而言,更是如此。如果你将方法定义为final的, 可以防止其他程序员在项目中通过继承来复用你的类。