-4

Hey guys I just wanted a quick reinsurance that this is correctly done:

So you have to find the error in the code segments -

Find the error in each of the following code segments:

//Superclass
public class Vehicle{
(member declarations…..)
}
//subclass
Public class car expands Vehicle{
(Member declarations….)
}

so isnt the error the fact its expands and should be extends instead correct??

3.  //superclass
public class Vehicle{
     private double cost; 
  public Vehicle(double c){
      cost = c;
}
(Other methods……)
}
//subclass
public class Car extends Vehicle{
    private int passengers;
   public Car(int p){
    passengers = c;
}
(Other methods…..)
}

Im not sure what the error is in this one, I got this wrong anyone have a clue??

4

2 回答 2

3

java中没有“expands”关键字。您总是必须使用extends类继承。

第二个示例中的类Car定义了一个新的构造函数。子类中的新构造函数必须将数据转发给父类构造函数,如下所示:

public Car(double c, int p) {
    super(c); // call the super constructor!
    passengers = p; // your normal constructor code
}
于 2012-10-11T16:26:54.707 回答
0

在 as 中添加一个额外的default构造函数Vehicle

  public Vehicle(){
     this.cost = 0.0;
  }

或者在Car构造函数中添加额外的 double 类型参数并按照@main 的建议调用 super--

您也可以将Car构造函数更新为:

public Car(int p) {
   super(0.0); 
   passengers = p; 
}
于 2012-10-11T16:34:05.173 回答