将子类或超类对象传递给方法(期望超类对象)

时间:2012-10-11 09:41:50

标签: java inheritance

我正在使用一些需要将超类或子类对象发送到方法的代码。

方法public void repair(Vehicle vehicle)将只访问超类对象中的方法。

public class Vehicle {
    //class stuff
}

public class Car extends Vehicle {
    //class stuff
}

public static void main(String[] args) 
{
    // do stuff to determine whether working with a vehicle or car
    if (someCondition)
    {
        Car = new Car();
        // do some stuff...
        repair(Car);
    }
    else
    {
        Vehicle = new Vehicle();
        // do some stuff...
        repair(Vehicle);
    }
}   

我想我有三个选择:

  1. 保持代码原样,它似乎正在工作。 - 我不喜欢这个选项,感觉我正在做出假设,我怀疑汽车只有方法可能被意外调用这样做,导致意外行为。
  2. 在car中创建一个getVehicle()方法,以返回Vehicle。然后使用repair(Car.getVehicle()); - 感觉好一点
  3. Car = new Car();更改为Vehicle = new Car();我相信会创建一个只能执行车辆类型方法的对象(车辆)。 - 这是最安全的,因为我现在限制可以做的事情,以防止意外行为。
  4. 3,这是最好的方法,因为修理方法只是期待车辆吗?

    另外,我可以/应该对public void repair(Vehicle vehicle)方法声明做什么吗?

    编辑:我似乎应该使用:

      

    保留代码

    因为repair()方法无论如何都将子类对象强制转换为超类对象。

1 个答案:

答案 0 :(得分:6)

没有修复的定义,但我认为你想要这样的东西

public abstract class Vehicle {
    //class stuff
}

public class Car extends Vehicle {
   //class stuff
}


public class Garage {
   public void repair(Vehicle vehicle){
   ....
   }
}

然后,您可以将Vehicle的任何子类传递给修复方法。在这种情况下它只是汽车,但你可以延伸到自行车,摩托车等。

现在您不需要使用if语句进行检查。您可以将对象(或Car或其他任何内容)传递到repair方法。

你刚刚成为

public static void main(String[] args)  {
    Garage g = new Garage();
    Vehicle c = new Car();
    Vehicle b = new Bike(); //assuming Bike is a subclass of Vehicle.
    g.repair(c);
    g.repair(b);
}  

如果在访问变量b和c时需要Car and Bike特定方法,那么您可以将其声明更改为

Car c = new Car();
Bike b = new Bike();
相关问题