为什么子类继承父类有错?

时间:2013-03-02 11:13:37

标签: parent subclass extend

如果继承TrainCar那就是问题。如果继承GCompoud就好了。哪里错了?

父:

public class TrainCar extends GCompound{

    public TrainCar(double size){

        engine =  new Engine(size);
        add(engine);
        }
}

子类:

public class Engine extends  TrainCar { 

    public Engine (double size){    //if inherit TrainCar that's a problem. 
                                    //if inherit GCompoud that's well.

        GPolygon engine = engine(size);     
        add(engine);
    }
}

Boxcar继承了TrainCar,这很好。

讲义#31:

public class Boxcar extends TrainCar {

 public Boxcar(Color color) {
}

http://www-cs-faculty.stanford.edu/~eroberts/courses/cs106a/handouts/30-graphical-structures.pdf

1 个答案:

答案 0 :(得分:0)

您必须在TrainCar的构造函数中调用Engine的构造函数。你可以这样做:

public Engine (double size) {
     super(size);

    GPolygon engine = engine(size);     
    add(engine);
}