簡體   English   中英

如何從超類獲取參數?

[英]How do I get parameters from the superclass?

好的,所以我有這個類別的Insurance及其構造函數。

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;
}
}

如何進行自動擴展保險課程? 我是否需要像這樣將超類的所有參數傳遞給子類?

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類。

因為Insurance的唯一public構造函數包含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;
}

如果將Auto歸為Insurance子類,那么您已經擁有的方法是最好的方法,即使從技術上講Java並不需要這樣做。

但是AutoInsurance嗎? 有一個設計問題。 也許Car需要一個Insurance來代替。 (或者Person 擁有 Auto擁有 Insurance )。

否。在保險中添加默認構造函數,不帶任何參數。 公共保險(){}

調用此構造函數將使用Insurance中的參數默認為null來初始化對象。

不,沒有必要。 這取決於您的班級設計。 您還可以使用構造函數鏈接重載超類中的構造函數。

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;
 }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM