二次分发举例

package com.starain.duotai;

/*按住F11快速调试debug as
* 按Ctrl+F11为Run as*/

/*抽象类*/
abstract class Driver {
public Driver() {
// 构造方法,方法名和类名完全相同,无任何返回类型,即使void类型都不行,能重载但是不能继承
}

public abstract void driversSay();// 抽象方法,只有abstract声明,但是没有实现
}

class MaleDriver extends Driver { // MaleDriver类继承抽象类Driver,必须进行所有抽象方法的重写

/* 对Driver抽象类中的抽象方法driversSay进行重写 */
@Override
public void driversSay() {
System.out.println("1111");// 如果是MaleDriver的实例对象,调用driversSay后输出1111
// drive
}
}

class FemaleDriver extends Driver {// femaleDriver类继承抽象类Driver,必须进行所有抽象方法的重写

/* 对Driver抽象类中的抽象方法driversSay进行重写 */
@Override
public void driversSay() {
System.out.println("2222");// 如果是FemaleDriver的实例对象,调用driversSay后输出2222
// drive
}

}

abstract class DriverTool {

private String type;

public DriverTool() {

}

public DriverTool(String type) {
this.setType(type);
}

public void setType(String type) {
this.type = type;
}

public String getType() {
return type;
}

public abstract void driverMethod(Driver driver);
}

class Car extends DriverTool {
public Car(){

}

@Override
public void driverMethod(Driver driver) {
driver.driversSay();
}

}

class Bus extends DriverTool {
public Bus(){

}

@Override
public void driverMethod(Driver driver) {
driver.driversSay();
}

}

public class DuoTaiTest {
public static void main(String[] args) {
Driver driver1 = new MaleDriver();
Driver driver2 = new FemaleDriver();
DriverTool tool1 = new Car();
DriverTool tool2 = new Bus();
tool1.driverMethod(driver1);
tool2.driverMethod(driver2);
driver1.driversSay();
driver2.driversSay();
}
}

你可能感兴趣的:(二次分发举例)