[英]Passing subclass or superclass object to method (expecting a superclass object)
I'm working with some code that needs to send either a superclass or subclass object to a method. 我正在处理一些需要将超类或子类对象发送给方法的代码。
The method public void repair(Vehicle vehicle)
will ONLY access methods in the super class object. 方法
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);
}
}
I figure I have three options: 我认为我有三个选择:
repair(Car.getVehicle());
repair(Car.getVehicle());
- this feels a little better Car = new Car();
Car = new Car();
to Vehicle = new Car();
Vehicle = new Car();
which I believe would create an object (vehicle) that can only perform methods of type vehicle. Is 3, the best approach, given that the repair method is only ever expecting vehicles? 鉴于维修方法只适用于预期的车辆,因此3是最佳方法吗?
Also, is there anything I could/should to to the: public void repair(Vehicle vehicle)
method declaration? 另外,有什么我可以/应该做的:
public void repair(Vehicle vehicle)
方法声明?
EDIT: It seems I should be using: 编辑:似乎我应该使用:
Leave the code as it is
保持原样
since the repair()
method casts the subclass object to a superclass object anyway. 因为
repair()
方法始终将子类对象转换为超类对象。
There is no definition of repair but I think you want something like this 没有维修的定义,但我认为您想要这样的东西
public abstract class Vehicle {
//class stuff
}
public class Car extends Vehicle {
//class stuff
}
public class Garage {
public void repair(Vehicle vehicle){
....
}
}
Then you can pass any subclass of Vehicle to the repair method. 然后,您可以将Vehicle的任何子类传递给修复方法。 In this case it is only Car but you could extend to have bike, motorcycle etc.
在这种情况下,只有汽车,但您可以扩展以拥有自行车,摩托车等。
Now you will not need to check with an if statement. 现在,您无需检查if语句。 You can just pass your object (or Car or anything else) into the
repair
method. 您可以将您的对象(或Car或其他任何东西)传递给
repair
方法。
You main just becomes 你主要变成
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);
}
If when accessing variable b and c you need Car and Bike specific method then you can change their declarations to be 如果在访问变量b和c时需要特定于Car和Bike的方法,则可以将其声明更改为
Car c = new Car();
Bike b = new Bike();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.