开发者

Java Inheritance Issue

Suppose I have the following classes:

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

Support I also have the method: queryCar()

private Object queryCar()
{
     int version = getCarVersion(); // returns car version
     if (version == 1)
         return new car1();
     else if (version == 2)
         return new car2();
     else i开发者_运维知识库f (version == 3)
         return new car3();
     ...
}

I have another method, 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. However, I only want one class to autogenerate that car on runttime. (Thinking of an analog of C++ pointers in java)


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:

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. In Java, everything automatically extends Object so you always have a common base class, but Object is probably not a particularly useful common base.

Generally, put common behaviour in, say, Car and add or override version-specific behaviour in each of the subclasses.

EDIT: In your doStuff method you should consider carefully whether you really need to inspect the subclass. 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. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜