覆盖具有不同参数数量的继承方法

时间:2019-05-13 17:25:28

标签: java inheritance abstract

有两个要解决的任务:

首先,应从类GeoObjects继承一个类矩形。 其次,应从类矩形继承类广场。

给出了抽象类GeoObjects。

abstract class GeoObjects{
    public abstract double Perimeter();
    public abstract double Surface();

    public static void main (String [] argv){
        double width = 4.0, height = 5.0, side= 3.0;
        GeoObject rectangle = new Rectangle (width, height);
        GeoObject square= new Square(side);

        System.out.println ("Perimeter = " + rectangle.Perimeter());
        System.out.println ("Surface= " + rectangle.Surface());
        System.out.println ("Perimeter= " + square.Perimeter());
        System.out.println ("Surface= " + square.Surface());
    }
}

class Rectangle extends GeoObjects{

    double width, height, side;

    Rectangle (double width, double height){
        this.width = width;
        this.height= height;
    }

    public double Perimeter (){
    return 2*(width+ height);
    }
    public double Surface(){
    return width* height;
    }
}

class Square extends Rectangle {

    double side;

    Square (double side){
        this.side= side;
    }
    public double Perimeter (){
        return 4*side;
    }
    public double Surface(){
        return side*side;
    }
}

我得到了编译器信息,即Square构造函数与Rectangle变量具有不同数量的变量。

我该如何解决这个问题而又不损害Square必须从矩形而不是GeoObjects继承的要求?

2 个答案:

答案 0 :(得分:5)

编译器错误消息通知您,您正在尝试使用与构造函数具有不同数量的参数来调用__REACT_ERROR_OVERLAY_GLOBAL_HOOK__中的超类构造函数。您没有在startReportingRuntimeErrors中显式调用超类构造函数,因此编译器已在Rectangle中插入了对默认超类构造函数的调用-有效地Square作为{{1}中的第一行}。

但是Rectangle中没有没有参数的构造函数;只有一个带有2个参数。通过两次将super();传递到Square()来适当地调用它。

您还将注意到,Rectangleside方法不再需要被覆盖,因为它们现在将使用超类中的正确值。

此外,常规的Java方法命名约定会让您以小写字母开头的方法命名为super()Perimeter

答案 1 :(得分:1)

要修复Square类,您将需要使用SELECT MAX(br1.id) /* Get last update of bonus */, br1.uid, br1.name, rb1.instance_id, rb1.player_id, br1.redeem_count, rb1.executed, rb1.completed, rb1.canceled FROM bonus_records br1 LEFT JOIN redeemed_bonuses rb1 ON rb1.bonus_id = br1.id WHERE (rb1.player_id IS NULL) OR /* never redeemed */ (rb1.player_id = 1 AND /* if redeemed then */ ( br1.redeem_count > ( /* total count of X redemed bonus is less then redeem_count but redeem_count <> 0 */ SELECT COUNT(*) FROM redeemed_bonuses rb2 INNER JOIN bonus_records br2 ON rb2.bonus_id = br2.id WHERE br2.uid = br1.uid AND rb2.completed = 0 AND rb2.canceled = 0 ) OR br1.redeem_count = 0 /* redeem_count = 0 means that there is no established limit of redeem */ ) ) GROUP BY br1.uid super(side, side)调用构造函数。您将不再需要Square内的side class变量,可以将其简化为:

平方:

Rectangle

矩形:

class Square extends Rectangle {

Square (double side){
    super(side,side);
 }
}

如果要重载Rectangle中的方法或将实现特定功能的方法放置为平方,则需要使用class Rectangle extends GeoObjects{ double width, height; Rectangle (double width, double height){ this.width = width; this.height= height; } public double Perimeter (){ return 2*(width+ height); } public double Surface(){ return width* height; } } width变量而不是side。