我不确定如何调用另一个类的抽象类中的setter方法。这就是我所拥有的:
public abstract class Media {
private String loanedTo;
public String getLoanedTo() {
return loanedTo;
}
public void setLoanedTo(String loanedTo) {
this.loanedTo = loanedTo;
}
private Date dueOn;
public Date getDueOn() {
return dueOn;
}
public void setDueOn(Date dueOn) {
this.dueOn = dueOn;
}
}
public class Library {
public void loan(Loanable item, String name){
Calendar calcDueDate = Calendar.getInstance();
calcDueDate.add(Calendar.DAY_OF_MONTH, item.getDaysToLoan());
dueOn = calcDueDate.getTime();
loanedTo = name;
}
}
如何从库中设置dueOn和loanedTo变量,这些变量不会扩展无法实例化的Media?我搜索时找不到答案。刚刚开始学习这些东西。
答案 0 :(得分:1)
好吧,你必须建立一个像
这样的具体课程public class Book extends Media {
}
如果您从未拥有抽象类的具体子类,则永远不能使用您的抽象类。
答案 1 :(得分:0)
这里可能存在一些误解。
回到您要求解决的问题,并确保您不打算将Library实现为扩展Media的类。
答案 2 :(得分:0)
如果您尝试实例化抽象Media类,则会失败(因为您无法实例化抽象类)。
如果你有一个具体的课程,说Book
,并且有extends Media
,那么你可以调用book.setLoanedTo("Bob")
和book.setDueOn(someJavaDate)
。
答案 3 :(得分:0)
尝试这样的事情:
public abstract class Media {
private String loanedTo;
public String getLoanedTo() {
return loanedTo;
}
public void setLoanedTo(String loanedTo) {
this.loanedTo = loanedTo;
}
private Date dueOn;
public Date getDueOn() {
return dueOn;
}
public void setDueOn(Date dueOn) {
this.dueOn = dueOn;
}
}
public class ConcreteMedia extends Media {
private String loanedTo;
public String getLoanedTo() {
return loanedTo;
}
public void setLoanedTo(String loanedTo) {
this.loanedTo = loanedTo;
}
private Date dueOn;
public Date getDueOn() {
return dueOn;
}
public void setDueOn(Date dueOn) {
this.dueOn = dueOn;
}
}
public class Library {
public void loan(Loanable item, String name){
Calendar calcDueDate = GregorianCalendar.getInstance();
calcDueDate.add(Calendar.DAY_OF_MONTH, item.getDaysToLoan());
Media concrete = new ConcreteMedia();
dueOn = concrete.setDueOn(calcDueDate.getTime());
loanedTo = concrete.SetLoanedTo(name);
}
}
答案 4 :(得分:0)
我认为您的Library.loan方法的Item参数需要具有您在抽象媒体中实现的方法。使用方法声明创建一个Loanable接口。如果需要,您可以让Media实现界面并保持抽象。
public interface Loanable {
String getLoanedTo();
void setLoanedTo(String loanedTo);
Date getDueOn();
void setDueOn();
}
public abstract class Media implements Loanable {
private String loanedTo;
public String getLoanedTo() {
return loanedTo;
}
public void setLoanedTo(String loanedTo) {
this.loanedTo = loanedTo;
}
private Date dueOn;
public Date getDueOn() {
return dueOn;
}
public void setDueOn(Date dueOn) {
this.dueOn = dueOn;
}
}
public class Library {
public void loan(Loanable item, String name){
Calendar calcDueDate = Calendar.getInstance();
calcDueDate.add(Calendar.DAY_OF_MONTH, item.getDaysToLoan());
dueOn = calcDueDate.getTime();
loanedTo = name;
item.setDueOn(dueOn);
item.setLoanedTo(loanedTo);
}