转储Java将无法编译

时间:2015-06-18 14:14:19

标签: java

我没有写这个应该编译的转储问题,并且是在最近的Java 8考试中,它给了我一些问题:

class Vehicle {
   String type = "4W";
   int maxSpeed = 100;

   Vehicle (String type, int maxSpeed){
      this.type = type;
      this.maxSpeed = maxSpeed;
      }
}

 class Car extends Vehicle {
    String trans;
    Car(String trans) {
    this.trans = trans;
    }

    Car(String type, int maxSpeed, String trans) {
    super(type, maxSpeed);
    this(trans);
    }
 }

 class Test {
    public static void main(String[] args) {

Car c1 = new Car("Auto");
Car c2 = new Car("4W", 150, "Manual");
System.out.println(c1.type + " " + c1.maxSpeed + " " + c1.trans);
System.out.println(c2.type + " " + c2.maxSpeed + " " + c2.trans);

    }

}

根据转储的答案应该是:

4W 150 Manual

相反,我得到:

Unresolved compilation problems: 
    Implicit super constructor Vehicle() is undefined. Must explicitly invoke another constructor
    Constructor call must be the first statement in a constructor

我到底做错了什么?

3 个答案:

答案 0 :(得分:3)

这个构造函数是问题所在:

Car(String trans) {
    this.trans = trans;
}

车辆中只有一个构造函数,它需要两个参数。您没有默认构造函数。因此,当您只使用一个参数调用Car构造函数时,编译器会查找不存在的默认构造函数。

您可以通过添加默认构造函数来修复它;像这样的东西:

class Vehicle {

   public static final String DEFAULT_TYPE = "4W";
   public static final int DEFAULT_SPEED = 100;
   protected String type;
   protected int maxSpeed;

   Vehicle() {
      this(DEFAULT_VEHICLE_TYPE, DEFAULT_SPEED);
   }

   Vehicle (String type, int maxSpeed){
      this.type = type;
      this.maxSpeed = maxSpeed;
   }
}

或者这样做:

Car(String trans) {
    super(trans, Vehicle.DEFAULT_SPEED);
    this.trans = trans;
}

答案 1 :(得分:1)

我认为这是您学校期望的完整代码。

由于Vehicle(),调用默认构造函数Vehicle(String, int)将自动调用this("4W", 100)

class Vehicle {
   String type;
   int maxSpeed;

    Vehicle (){
        this("4W", 100);   //Set your default values here..
    }
    Vehicle (String type, int maxSpeed){
      this.type = type;
      this.maxSpeed = maxSpeed;
    }
}

你的汽车课:

super()也可以省略,因为即使你不包括它,也会隐含地为你调用它。

class Car extends Vehicle {
    String trans;

    Car(String trans) {
        super();   //Optional
        this.trans = trans;
    }

    Car(String type, int maxSpeed, String trans) {
        super(type, maxSpeed);
        this.trans = trans;
    }
}

<强>输出:

4W 100 Auto
4W 150 Manual

答案 2 :(得分:1)

我从这里看到你的误解。

Car(String type, int maxSpeed, String trans) {
    super(type, maxSpeed);   //cannot use super() & this() concurrently
    this(trans);             //cannot use super() & this() concurrently
}

Java不允许在同一个构造函数中同时调用super()this()

super()表示从父类调用构造函数。 this()表示在您自己的类中调用另一个构造函数。

因为那些实际上是在调用构造函数,所以它们需要位于代码的第一行。

因此,您只能拨打super()this()。你不能在同一个构造函数中同时拥有它们。如果允许,你基本上是在两次调用构造函数,当发生这种情况时,会出现歧义。

你的班级应该使用哪种构造函数?

相关问题