【问题标题】:Passing subclass or superclass object to method (expecting a superclass object)将子类或超类对象传递给方法(期望超类对象)
【发布时间】:2012-10-11 09:41:50
【问题描述】:

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

方法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();,我相信这会创建一个只能执行车辆类型方法的对象(车辆)。 - 这感觉最安全,因为我现在限制可以做的事情,以防止意外行为。

考虑到维修方法只针对车辆,3 是最好的方法吗?

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

编辑:看来我应该使用:

保持代码不变

因为repair() 方法将子类对象转换为超类对象。

【问题讨论】:

  • 你的修复方法是什么样的?
  • 当 Car 进入修复方法时,无论如何它都会隐式转换为 Vehicle。所以你不可能在 repair 方法中调用 Car 方法。
  • 我认为 Car 应该扩展 Vehicle。
  • @NandkumarTekale 同意了。虽然我认为这是一个错字。
  • 是的,Car Extends Vehicle,是的,这是一个错字(我意识到一个非常重要的错字)!编辑以反映这一点...

标签: java inheritance


【解决方案1】:

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

public abstract class Vehicle {
    //class stuff
}

public class Car extends Vehicle {
   //class stuff
}


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

然后您可以将 Vehicle 的任何子类传递给 repair 方法。在这种情况下,它只是汽车,但您可以扩展到拥有自行车、摩托车等。

现在您不需要使用 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 和 Bike 的方法,那么您可以将它们的声明更改为

Car c = new Car();
Bike b = new Bike();

【讨论】:

  • 感谢您的回答。我可能没有说清楚,但需要 if 语句来确定创建哪个对象。然后在调用 repair() 之前完成其他事情(在 Car 或 Vehicle 对象上)
  • 其他什么东西?可以将其拉入 Vehicle 类中的通用方法中吗?如果你需要 if 那么你可以在里面做这个特定的东西。但是你应该可以在 if 语句之外调用 Repair
猜你喜欢
  • 1970-01-01
  • 2010-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 2017-12-14
相关资源
最近更新 更多