我是Java编程的新手,试图掌握OOP的诀窍。

所以我创建了这个抽象类:

public abstract class Vehicle{....}

和2个子类:

public class Car extends Vehicle{....}
public class Boat extends Vehicle{....}

Car和Boat还拥有一些不常见的独特字段和方法(没有相同的名称,所以我无法在Vehicle中为它们定义抽象方法)。

现在在mainClass中我已经设置了我的新车库:

Vehicle[] myGarage= new Vehicle[10];
myGarage[0]=new Car(2,true);
myGarage[1]=new Boat(4,600);

我对多态性非常满意,直到我尝试访问Car特有的一个字段,例如:

boolean carIsAutomatic = myGarage[0].auto;

编译器不接受。我使用类型转换解决了这个问题:

boolean carIsAutomatic = ((Car)myGarage[0]).auto;

工作……但它对方法没有帮助,只对字段有帮助。意思是我做不到

(Car)myGarage[0].doSomeCarStuff();

我的问题是,我的车库里到底有什么?我试图获得直觉,并理解“幕后”发生了什么。


为了方便以后的读者,以下是对答案的简要总结:

Yes, there's a Car in myGarage[] Being a static typed language, the Java compiler will not lend access to methods/fields that are non-"Vehicle", if accessing those through a data structure based on the Vehicle super class( such as Vehicle myGarage[]) As for how to solve, there are 2 main approaches below: Use type casting, which will ease the compiler's concerns and leave any errors in the design to run time The fact that I need casting says the design is flawed. If I need access to non-Vehicle capabilities then I shouldn't be storing the Cars and Boats in a Vehicle based data structure. Either make all those capabilities belong to Vehicle, or use more specific (derived) type based structures In many cases, composition and/or interfaces would be a better alternative to inheritance. Probably the subject of my next question... Plus many other good insights down there, if one does have the time to browse through the answers.


当前回答

我是Java编程的新手,试图掌握OOP的诀窍。

这只是我的观点——我将尽量简短,因为很多有趣的事情已经说过了。但实际上,这里有两个问题。一个是关于“面向对象”的,一个是关于它如何在Java中实现的。

首先,是的,你的车库里有辆车。所以你的假设是对的。但是,Java是一种静态类型语言。而编译器中的类型系统只能通过相应的声明来“知道”各种对象的类型。不是他们的习惯。如果你有一个Vehicle数组,编译器只知道它。所以它会检查你只在任何车辆上执行允许的操作。(换句话说,方法和属性在Vehicle声明中可见)。

你可以通过显式类型转换(Car)向编译器解释“你实际上知道这个Vehicle是Car”。编译器会相信你——即使在Java中有一个在运行时的检查,这可能会导致一个ClassCastException,以防止进一步的损害,如果你撒谎(其他语言,如c++不会在运行时检查-你必须知道你在做什么)

最后,如果你真的需要,你可以依靠运行时类型标识(即:instanceof)在尝试强制转换之前检查对象的“真实”类型。但在Java中,这通常被认为是一种糟糕的实践。

正如我所说,这是实现OOP的Java方式。有完全不同的类语言家族,通常被称为“动态语言”,它们只在运行时检查是否允许对对象进行操作。使用这些语言,您不需要将所有公共方法“上移”到某些(可能是抽象的)基类来满足类型系统。这就是所谓的鸭子打字。

其他回答

如果你使用Java,可以使用反射来检查一个函数是否可用并执行它

要回答你的问题,你可以找到你的车库里到底有什么,你可以做下面的事情:

Vehicle v = myGarage[0];

if (v instanceof Car) {
   // This vehicle is a car
   ((Car)v).doSomeCarStuff();
} else if(v instanceof Boat){
   // This vehicle is a boat
   ((Boat)v).doSomeBoatStuff();
}

更新:正如你可以从下面的评论中读到的,这种方法对于简单的解决方案是可以的,但它不是一个好的实践,特别是如果你的车库里有大量的车辆。所以,只有在你知道车库不会太大的情况下才使用它。如果不是这样,在堆栈溢出时搜索“avoid instanceof”,有多种方法可以做到这一点。

你问管家:

吉夫斯,还记得我在爪哇岛的车库吗?去看看第一辆停在那里的车是不是自动挡的。

懒惰的吉夫斯说:

但是,先生,如果这是一辆既不能自动也不能非自动的车呢?

这是所有。

好吧,这还不是全部,因为现实中更多的是鸭子类型而不是静态类型。这就是为什么我说吉夫斯很懒。

创建车辆级别字段,这将有助于使每个单独的车辆更加独特。

public abstract class Vehicle {
    public final boolean isCar;
    public final boolean isBoat;

    public Vehicle (boolean isCar, boolean isBoat) {
        this.isCar  = isCar;
        this.isBoat = isBoat;
    }
}

将继承类中的Vehicle level字段设置为适当的值。

public class Car extends Vehicle {
    public Car (...) {
        super(true, false);
        ...
    }
}

public class Boat extends Vehicle {
    public Boat (...) {
        super(false, true);
        ...
    }
}

实现使用车辆级别字段正确地破译车辆类型。

boolean carIsAutomatic = false;

if (myGarage[0].isCar) {
    Car car = (Car) myGarage[0];
    car.carMethod();
    carIsAutomatic = car.auto;
}

else if (myGarage[0].isBoat) {
    Boat boat = (Boat) myGarage[0];
    boat.boatMethod();
}

因为你告诉编译器车库中的所有东西都是Vehicle,所以你只能使用Vehicle类级别的方法和字段。如果你想正确地破译车辆类型,那么你应该设置一些类级别的字段,例如isCar和isBoat,这将使你的程序员更好地理解你正在使用的车辆类型。

Java是一种类型安全的语言,所以在处理像Boats和Cars这样已转换的数据之前,最好总是进行类型检查。

如果对基类型进行操作,则只能访问它的公共方法和字段。

如果你想访问扩展类型,但有一个基类型的字段存储它(在你的情况下),你首先必须强制转换它,然后你可以访问它:

Car car = (Car)myGarage[0];
car.doSomeCarStuff();

或更短,没有温度字段:

((Car)myGarage[0]).doSomeCarStuff();

由于您使用的是Vehicle对象,所以只能从它们的基类调用方法,而不能强制转换。因此,对于车库来说,最好区分不同数组(或者更好的列表)中的对象——数组通常不是一个好主意,因为它在处理方面远不如基于collection的类灵活。