Equilateral和IsoscelesRight类扩展了Triangle类。我不知道如何使用super()方法。我应该使用它,但它让我困惑。它的目的是什么?我怎样才能使它工作?我是否必须重命名实例变量?当我尝试编译它说它不识别符号超级。 谢谢你的帮助。
public class Triangle
{
// instance variables
private double sideA, sideB, sideC;
public Triangle(double side1, double side2, double side3)
{
// initialise instance variables
sideA = side1;
sideB = side2;
sideC = side3;
}
public double getSideA()
{
return sideA;
}
public double getSideB()
{
return sideB;
}
public double getSideC()
{
return sideC;
}
}
public class Equilateral extends Triangle
{
// instance variables
private double side1, side2, side3;
/**
* Constructor for objects of class box
*/
public Equilateral(double sideA)
{
// call superclass
super(sideA);
// initialise instance variables
side1 = sideA;
side2 = sideA;
side3 = sideA;
}
}
public class IsoscelesRight extends Triangle
{
// instance variables
private double sideA, sideB, sideC;
/**
* Constructor for objects of class box
*/
public IsoscelesRight(double side1, double side2)
{
// call superclass
super(side1);
// initialise instance variables
sideA = side1;
sideB = side1;
sideC = Math.pow(sideA*2,2);
}
}
答案 0 :(得分:2)
这里有几件事情:
您可以简单地将它们定义为:
public class Equilateral extends Triangle
{
public Equilateral(double sideA)
{
super(sideA, sideA, sideA);
}
}
public class IsoscelesRight extends Triangle
{
public IsoscelesRight(double sideA)
{
super(sideA, sideA, Math.sqrt(2*sideA*sideA));
}
}
然后通过getSideA
等getter访问边长。
答案 1 :(得分:1)
// call superclass
super(sideA);
是父构造函数调用,但是超类中没有构造函数只接受一个双参数。