如何从超类中获取参数?

时间:2014-07-10 22:46:22

标签: java class inheritance parameters super

好的,我有这个类保险及其构造函数。

public class Insurance
{
protected String pNum, pDate;
protected int yPrem;

public Insurance(String pNum, String pDate, int yPrem)
{
    this.pNum = pNum;
    this.pDate = pDate;
    this.yPrem = yPrem;
}
}

如何制作Auto extends Insurance课程?我是否需要将超类的所有参数传递给子类?

public class Auto extends Insurance
{
private String vehicleID, make, model;
private int year, accidents, age;

public Auto(String pNum, String pDate, int yPrem, String vehicleID,
        String make, String model, int year, int accidents)
{
    super(pNum, pDate, yPrem);
    this.vehicleID = vehicleID;
    this.make = make;
    this.model = model;
    this.year = year;
    this.accidents = accidents;
    age = 2014-year;
}
}

Auto的参数列表真的需要包含超类中的所有参数吗? 为了澄清,还有一个Property类扩展了Insurance类。

3 个答案:

答案 0 :(得分:1)

因为public的唯一Insurance构造函数包含3个参数,Auto构造函数必须调用它,传递3个参数。

但这些论点在技术上不一定来自Auto构造函数本身。虽然让它们来自Auto构造函数的参数是有意义的,但是可以从技术上传递文字,但这在这里没有多大的逻辑意义,因为这会限制传递给Insurance的内容。

public Auto(String vehicleID,
    String make, String model, int year, int accidents)
{
    super("someNumber", "20140710", 500);
    this.vehicleID = vehicleID;
    this.make = make;
    this.model = model;
    this.year = year;
    this.accidents = accidents;
    age = 2014-year;
}

如果AutoInsurance的子类,那么你已经拥有它的方式是最好的方法,即使技术上不需要Java那样。

但是AutoInsurance?有一个设计问题。也许Car需要拥有 Insurance。 (或Person Auto Insurance}。

答案 1 :(得分:0)

没有。在Insurance中添加默认构造函数,不带任何参数。 公共保险(){ }

调用此构造函数将使用Insurance默认为null的参数初始化对象。

答案 2 :(得分:0)

不,没有必要。这取决于你班级的设计。您还可以使用构造函数链来重载超类中的构造函数。

public class Insurance
{

  protected String pNum, pDate;
  protected int yPrem;

  public Insurance()
  {
  this("10", "10-10-10", 10)
  }

  public Insurance(String pNum, String pDate, int yPrem)
  {
  this.pNum = pNum;
  this.pDate = pDate;
  this.yPrem = yPrem;
  }

}

在这种情况下,您的子类应定义如下:

  public class Auto extends Insurance
  {
      private String vehicleID, make, model;
      private int year, accidents, age;

  public Auto(String vehicleID, String make, String model, int year, int accidents)
 {

 super(); //If a constructor does not explicitly invoke a superclass constructor, the
         //compiler automatically inserts a call to the no-argument constructor of the
          // superclass
 this.vehicleID = vehicleID;
 this.make = make;
 this.model = model;
 this.year = year;
 this.accidents = accidents;
 age = 2014-year;
 }

}
相关问题