[英]Having inheritance and polymorphism issues with Java
我还需要重写calclatefees方法来计算过期电影的滞纳金。
public class Action extends Movie {
protected double latecost;
protected double latefees;
public Action (String title, String rating, int id, int rentTime,
double latecost, double latefees ) {
super(title, rating, id, rentTime);
this.title = title;
this.rating= rating;
this.id = id;
this.rentTime= 8;
this.latecost = 2;
System.out.println( "Overridden " + title + rating + " " + id + " "
+ latecost + " " + latefees);
}
public double calclatefees (double latecost) {
if (rentTime > 3)
latefees = ((rentTime - 3) * latecost);
return latefees;}
@Override
public String toString () {
String x = "Movie: " + title + " is rated " + rating + "\nMovie ID number:"
+ id + " late fees are $" + latefees;
return x;
}
}
当前此打印:
overloaded - not overridden NR 00
overridden
这是完美的。 它说明了对构造函数的特殊对待。 它们都首先调用父构造函数。
因此,您会看到Movie
打印的构造函数过载-未覆盖NR 00 ,然后Action
的构造函数启动并覆盖打印。
您需要使用this关键字。 我相信,如果您不这样做,并且在构造函数中使用的是相同的名称,则它不会分配任何内容。 您正在告诉参数中的标题等于您为其分配的标题,在下面的示例中该标题为“未覆盖”。
例如
public Movie(String title, String racing, int id, int rentTime){
this.title = " not overridden ";
// probably should be something like this.title = title after debugging.
//etc...
}
this关键字引用当前对象的数据成员,因此this.title将是Movie的标题,而不是参数成员的标题。
您还需要使用上面的set方法来执行此操作。
public void rating (String rating) {this.rating = rating;}
编辑:尝试构造函数
public Movie(String title, String rating, int id, int rentTime){
this.title = " not overridden ";
this.rating = " NR ";
this.id = 0;
this.rentTime = 0;
System.out.println( " overloaded -" + title + rating + id + rentTime);
}
在看到输出之后,如果要显示要传递给其他子类的实际值,则必须将其更改为:
public Movie(String title, String rating, int id, int rentTime){
this.title = title;
this.rating = rating;
this.id = id;
this.rentTime = rentTime;
System.out.println( " overloaded -" + title + rating + id + rentTime);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.