[英]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.