简体   繁体   English

Java继承问题

[英]Java Inheritance Issue

Suppose I have the following classes: 假设我有以下课程:

class car1 {}
class car2 {}
class car3 {}
class car4 {}

Support I also have the method: queryCar() 支持我也有方法:queryCar()

private Object queryCar()
{
     int version = getCarVersion(); // returns car version
     if (version == 1)
         return new car1();
     else if (version == 2)
         return new car2();
     else if (version == 3)
         return new car3();
     ...
}

I have another method, doStuff() 我有另一种方法doStuff()

private void doStuff()
{
     // psudocode
     if queryCar() returns a car1, I want to create a JPanel with an instance member of type car1
}

How do I accomplish said psudocode? 我如何完成所说的伪代码? InstanceOf works for determining the class. InstanceOf用于确定类。 However, I only want one class to autogenerate that car on runttime. 但是,我只希望一个类在运行时自动生成该车。 (Thinking of an analog of C++ pointers in java) (在Java中思考C ++指针的类似物)

You should use inheritance do do what you need. 您应该使用继承来做您需要的事情。

abstract class Car {
    public Car queryCar();
    public int getCarVersion();
    public void doStuff() {
        JPanel j = new JPanel();
        j.add(new JLabel(queryCar().getCarVersion()));
    }
}

class Car1 extends Car {
    public Car queryCar() { return new Car1(); }
    public int getCarVersion() { return 1; }
}

You can do this using instanceof with Object like you did, but it might make it easier to use a car interface like this: 您可以像使用Object那样使用instanceof来执行此操作,但是这样可以更轻松地使用如下所示的car接口:

interface Car {}
class Car1 implements Car {}

private void doStuff {
    Car car = queryCar();
    if(car instanceof Car1) {
        Car1 theCar = ((Car1) car);
        theCar.car1OnlyMethod();
        //Or
        ((Car1) car).car1OnlyMethod();
    }
}

It depends on how much common behaviour you have between your carN classes. 这取决于您的carN类之间有多少共同行为。 In Java, everything automatically extends Object so you always have a common base class, but Object is probably not a particularly useful common base. 在Java中,一切都会自动扩展Object,因此您始终拥有一个通用的基类,但是Object可能不是一个特别有用的通用基。

Generally, put common behaviour in, say, Car and add or override version-specific behaviour in each of the subclasses. 通常,将常见行为放入例如Car并在每个子类中添加或覆盖特定于版本的行为。

EDIT: In your doStuff method you should consider carefully whether you really need to inspect the subclass. 编辑:在您的doStuff方法中,您应该仔细考虑是否真的需要检查子类。 It will be difficult to maintain if you do require different behaviour for each subclass, so you should think about whether you can move some logic into the carN classes or the Car superclass and remove the dependency. 如果确实对每个子类要求不同的行为,将很难维护,因此您应该考虑是否可以将某些逻辑移入carN类或Car超类并删除依赖项。 If you can write your doStuff in terms of a more general Car interface/superclass then your code will be cleaner and easier to understand and maintain. 如果您可以使用更通用的Car接口/超类来编写doStuff ,那么您的代码将更加简洁,易于理解和维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM