使用构造函数

时间:2016-03-01 03:17:47

标签: inheritance polymorphism super

嘿伙计们,所以我正在研究一个带有形状的简单java继承程序。我知道我的问题并不新鲜,但我研究过,通常的问题是super参数不匹配父类的构造函数参数类型。但是,我有匹配的参数,仍然会收到此错误。错误发生在Parallelogram中的超级语句中。非常感谢任何帮助,谢谢!

public abstract class Quadrilateral implements Shapes
{
double base, height, perimeter, area, s1, s2, s3, s4;
String name;

 public Quadrilateral(String name, double base, double height, double side1, double side2, double side3, double side4){
   this.name = name;
   this.base = base;
   this.height = height;
   s1 = side1;
   s2 = side2;
   s3 = side3;
   s4 = side4;

}



public double getHeight(){
   return height;
}

public double getS1(){
    return s1;
}

public double getS2(){
    return s2;
}

public double getS3(){
    return s3;
}

public double getS4(){
    return s4;
}

public double getPerimeter(){
    return s1 + s2 + s3 + s4;
}

public String toString(){
    String str;
    str = "name is " + name + "\n";
    str += "area is " + area + "\n";
    str += "perimeter is " + perimeter + "\n";
    str += "sides 1-4 are " + s1 + ", " + s2 + ", " + s3 + "and " + s4;

    return str;
}
}

新班级

public class Parallelogram extends Quadrilateral
{

public Parallelogram(String name, double base, double height){

super(name, side1, side2, side1, side1, side2, side2); //RECIEVE ERROR HERE WITH THE FIRST SIDE1!!!

}

public double getArea(){
area = base * height;
return area;    
}

public String getName(){
    return name;
}


}

新班级

public class Rectangle extends Parallelogram
{
 public Rectangle(String name, double side1, double side2){
     super(name, side1, side2);
    }
}

新班级

public class Square extends Rectangle
{
public Square(String name, double side1){
    super(name, side1, side2);
}
}

2 个答案:

答案 0 :(得分:0)

您正在将值传递给未在Parallelogram构造函数中定义的基础构造函数 - 即side1side2。一种选择是改变

public Parallelogram(String name, double base, double height){

super(name, side1, side2, side1, side1, side2, side2); //RECIEVE ERROR HERE WITH THE FIRST SIDE1!!!

}

public Parallelogram(String name, double base, double height, double side1, double side2){

super(name, base, height, side1, side1, side2, side2); 

}

,同样适用于RectangleSquare

答案 1 :(得分:0)

你有没有理由不使用" this.s1"您的四边形课程中的关键字? 另外,您是否打算在任何子类中声明All的抽象方法?

此外,您应养成将实例变量声明为私有的习惯,这是一种很好的做法,并促进数据封装(数据隐藏)。

如果您将所有子类扩展为四边形,我认为这将是一个更好的程序。而不是四边形延伸平行四边形延伸矩形延伸正方形等。 享受!