-2

我有以下问题。我必须在 makeLeftTurnMethod 内部进行投射......这对我来说看起来很丑陋......有没有办法让我不必这样做?

public interface Car(){
   public void turnRight();
   public void turnLeft();
   public void go();
}
public class LuxuryCare implements Car(){
   public void systemCheckRightSideClear();
   public void systemCheckLeftSideClear();
}
public class UsedCar implements Car(){
   public void personCheckRightSideClear();
   public void personCheckLeftSideClear();
}

public interface Run{
  public void makeLeftTurn();
}
public class RunLuxuryCar implements Run{
  public void makeLeftTurn(Car car){
     car = (LuxuryCar)car;
     car.systemCheckLeftSideClear();
     car.turnLeft();
  }
}

public class RunUsedCar implements Run{
   public void makeLeftTurn(Car car){
       car = (UsedCar)car;
       car.personCheckLeftSideClear();
       car.turnLeft();
   }
}

public void tester(){
    //Could return either used or luxuy car 
    Run run = RunFactory.getInstance(UsedCar);
    Car car = CarFacory.getInstance(usedCar);
    run.makeLeftTurn(car);
}
4

2 回答 2

1

这是我对您的意图的最佳猜测,修复了语法错误并使用泛型来消除强制转换:

public static interface Car{
    public void turnRight();
    public void turnLeft();
    public void go();
 }

 public abstract class LuxuryCar implements Car{
    public void systemCheckRightSideClear(){}
    public void systemCheckLeftSideClear(){}
 }

 public abstract class UsedCar implements Car{
    public void personCheckRightSideClear(){};
    public void personCheckLeftSideClear(){};
 }

 public interface Run<T extends Car> {
   public void makeLeftTurn(T car);
 }

 public class RunLuxuryCar implements Run<LuxuryCar>{
   @Override
   public void makeLeftTurn(LuxuryCar car){
      car.systemCheckLeftSideClear();
      car.turnLeft();
   }
 }

 public class RunUsedCar implements Run<UsedCar>{
    @Override
    public void makeLeftTurn(UsedCar car){
        car.personCheckLeftSideClear();
        car.turnLeft();
    }
 }
于 2013-02-13T07:52:02.597 回答
0

简单的答案是你的接口应该总是表达所有可以执行的操作。如果某些实现实现某些方法没有意义,那么您的抽象是错误的。在这种情况下,您的问题表明您的Car接口需要isLuxuryCar()isUsedCar()方法,以便您可以分辨出区别,以及需要为每个方法调用的适当方法。

更进一步,这不是继承的真正用途。您所展示的内容是我希望在教科书或 Java 入门书中找到的内容,这是对继承用途的错误看法。继承和多态都是关于代码重用的,我发现发现继承关系的频率比他们计划的要多得多。当您发现您在相关对象中编写类似代码时,您会发现它们,此时您从它们中提取一个公共超类以将代码合并到一个位置。

于 2013-02-13T03:23:19.473 回答