【问题标题】:Having inheritance and polymorphism issues with JavaJava 存在继承和多态性问题
【发布时间】:2016-05-06 16:00:49
【问题描述】:

我还需要一个覆盖的 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;
    }
   }    

【问题讨论】:

  • 一些输出会有帮助。
  • 抛开您遇到的问题,考虑将动作、喜剧和戏剧重构为枚举器,这是电影的更好属性,而不是继承的电影... :)
  • 我想看看为什么我的 toString 没有发回我放在重载构造函数中的值,以及为什么当我在我的 super 中分配它们时它们仍然不会发回。

标签: java inheritance polymorphism


【解决方案1】:

目前打印:

overloaded - not overridden  NR 00
overridden 

这是完美的。它表明构造函数被特殊对待。他们都先调用父构造函数。

因此,您会看到 Movie 的构造函数打印重载 - 未覆盖 NR 00,然后 Action 的构造函数启动并打印 overridden

【讨论】:

    【解决方案2】:

    您需要使用 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 将是电影的标题,而不是参数成员标题。

    您还需要使用上面设置的方法来执行此操作。

    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);
     }
    

    【讨论】:

    • 我可以让我的子类 toStrings 打印我的数组主方法中的值吗?
    • 是的,但是现在您没有要打印的值。您的 toString 方法现在是否显示任何内容?也许只是您输入的字符串文字?还要确保在你的 toString 方法之上你有 @Override 注释
    • 我有@Override,但我如何显示的不仅仅是文字?
    • 就像我说的,您必须更改 Movie 的构造函数。您必须使用 this 关键字来分配标题和此类值。我将在上面进行编辑,您可以尝试一下。
    • 我一直在努力,但我的 calclatefees 不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    相关资源
    最近更新 更多