我有一个带有超类,子类和驱动程序类的接口。该接口必须在子类中实现,但是,我对该如何执行感到困惑。是否在超类中实现接口,然后扩展子类? 该超类称为存储。
子类称为Retail,它应该接收超类的构造函数,所售商品的数量,单价和售价应为数组参数。此类实现在接口上定义的两个方法。
接口应该有两种方法。一种是利润,另一种是工资。利润法是每周计算商店利润,而工资法是一周计算商店经理的工资。
/*
The interface should have two methods.
One is the “Profit” and the other is “Salary”.
The profit method is to calculate the store profit in a week, and salary method
is to calculate the store manager’s salary in a week.
*/
public interface Interface {
public void profit();
public void salary();
}
/*
The store class is a super class that receives store location,
manager name, hours worked, and hour rate.
This class should have the constructor that receives all of these.
It also should have get and set methods for each of fields.
This class also has “toString()” to
display restaurant location and manager’s name.
*/
public class Store {
private String location;
private String manager;
private int hours;
private int rate;
public Store(String l, String m, int hrs, int r) {
location = l;
manager = m;
hours = hrs;
rate = r;
}
public void setLocation(String l) {
location = l;
}
public String getLocation() {
return location;
}
public void setName(String m) {
manager = m;
}
public String getName() {
return manager;
}
public void setHours(int hrs) {
hours = hrs;
}
public int getHours() {
return hours;
}
public void setRate(int r) {
rate = r;
}
public int getRate() {
return rate;
}
public String toString() {
String result = "Store Location: " + location + "\n";
result += "Manager name:" + manager + "\n";
return result;
}
}
public class Retail extends Store {
private int items;
private double unit;
private double sale;
public Retail(String l, String m, int hrs, int r,int i, double u, double s){
super(l,m, hrs, r);
items = i;
unit = u;
sale = s;
}
public void profit() {
double[][] money = {{1.99, 2.99, 3.99, 4.99},
{5.99, 6.99, 7.99, 8.99},
{150, 48, 350,20}};
for (int i = 0; i < money.length; i++) {
for (int j = 0; j < money[i].length; j++) {
sum += money[i][j];
}
}
double profit = items * ( s - u);
}
public void salary() {
double pay = hrs * r;
//double salary = pay - ( pay * 0.05);
}
public double getSalary() {
double baseSalary = super.getHours();
}
public String toString() {
result += super.getName(); // inherited from superclass
String result = "Total Benefit: " + profit + "\n";
result += "Salary: " + salary + "\n";
return result;
}
}
答案 0 :(得分:2)
interface
合同适用于整个层次结构,则implement
可以在超类中使用,所有子类都将自动遵守interface
合同。interface
,但是如果它没有足够的细节来实现abstract
方法,则使超类interface
成为可能。这样,您可以强制子类遵守interface
合同。interface
合同与整个层次结构完全不相关,则仅在适用的子类中实施。在您的示例中,问题是接口方法profit()
和salary()
是否适用于任何类型的Store
?如果是(我认为是),则继续在超类中实现。但是,您可能无法使用可用的数据点在profit()
类中计算salary()
和Store
。因此,您可以选择将Store
类声明为抽象类。如果可以实现这些方法,则可以使Store
类具体化。
另一方面,如果接口方法profit()
和salary()
可能不适用于所有类型的Store
,则继续执行interface
Retail
类。
尽管我认为第一个选择是不错的选择,但是根据业务场景选择是您的选择。