簡體   English   中英

建模繼承層次結構…Java

[英]modeling a inheritance hierarchy… java

奧什科什的住宿可分為三類:酒店(根據房間數量和星級評定),旅館(根據房間數量以及是否提供自行車租賃)以及Bed-n-Breakfasts(根據數量)房間數量以及是否允許延遲入住)。 每個房間每晚的價格始終是固定的,酒店,旅館和Bed-n-Breakfasts的價格分別為40美元,20美元和55美元。用於模擬這種情況的繼承層次結構的框架代碼如下。 完成所有缺少的部分,以便代碼進行編譯,對繼承層次結構建模並具有上述所有功能。 您應該確定適當的數據成員存儲在哪些類中,以及這些數據成員的類型。 在每個類中,完成構造函數並提供一個方法computeRate,該方法將花費的住宿天數作為參數,並返回該住宿的總房費。不應提供其他方法。

有人可以給我一些關於天氣的提示,您認為我正在以正確的方式解決這個問題。 我遇到的主要問題是computeRate方法。 我不確定如何設置酒店,Bed-n-早餐和旅館的住宿價格。 我嘗試使用超級,但我不能完全確定這是否是我應該做的。

//父類

public class Lodging
{
    int sum;
    int price;
    public Lodging( int price ) {
        this.price = price;
    }
}

public double computeRate(int numberOfNights){

    price *= numberOfNights;
    return sum;
}

//子類

public class Hostel extends Lodging
{
    private int numberOfRooms;
    private boolean bikeRentals;

    public Hostel( int rooms, boolean rentals) { 
        super(20);
        this.numberOfRooms = rooms;
        this.bikeRentals = rentals;   
    }  
}  

//子類

public class Hotel extends Lodging
{
    private int rooms;
    private int starRating;

    public Hotel( int rooms, int starRating ) {
        super(40);
        this.rooms = rooms;
        this.starRating = starRating;
    } 
}

//子類

public class BednBreakfast extends Lodging
{
    private int numberOfRooms;
    private boolean lateArrivals;

    public BednBreakfast( int rooms, boolean late ){
        super(55);
        this.numberOfRooms = rooms;
        this.late = late;

這是給定的骨架代碼

  class Lodging
  { 
         public Lodging(                   ) 
         { 

         } 
  }//End class Lodging 

  class Hotel 
  { 
         public Hotel(                    ) 
         {

         } 
  }//End class Hotel 

  class Hostel 
  {
         public Hostel(         ) 
         { 

         } 
  }//End class Hostel 

  class BednBreakfast 
  { 
         public BednBreakfast (       ) 
         { 

         } 
  }//End class BednBreakfast

您的每個類都有房間,因此我將其移至父類,然后將其添加到構造函數中。

此外, Lodging是一個抽象概念,因此您無法創建new Lodging() ,而需要一個特定的實例。

public abstract class Lodging {
    private double nightlyRate;
    private int capacity;

    public Lodging( int capacity, double rate ) {
        nightlyRate = rate;
        this.capacity = capacity;
    }

    public double computeRate(int numberOfNights){
        return this.nightlyRate * numberOfNights;
    }
}

然后,對於Hostel示例, super(rooms, 20)沒問題。 它正確設置了父類的字段,並且每個子類都將繼承超類的computeRate()方法。 問題描述並不表示需要覆蓋它。

暫無
暫無

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

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