从超类调用变量到子类

时间:2016-06-10 03:41:41

标签: java inheritance subclass superclass

我没有运气从我的超类调用变量到我的子类。任何人都可以帮忙吗?

//SUPERCLASS
public class Circle {

  protected double radius;
  protected double area;

  //Some code to construct object and initialize radius

  //Return Calculated Area
  protected double getArea() {
    area = Math.pow(radius, 2) * Math.PI;
    return area;
  }

}

//SUBCLASS
public class Cone extends Circle {

  private double height;

//Some more code with constructors and different methods

  public double getVolume() {
    {
      return (area * height / 3)
    }
  }

代码还有很多,但我遇到的主要问题是在子类中,'area'变量是0.00而且我不确定如何使它等于'area'计算的超类

5 个答案:

答案 0 :(得分:1)

尝试:

public double getVolume() {
   return (getArea() * height / 3)
}

此外:圆圈应该在构造函数中用半径初始化,而不是字段区域,因为它取决于半径:

public class Circle {

  protected final double radius;

  public Circle(double radius) {
    this.radius = radius
  }

  public double getArea() {
    return Math.pow(radius, 2) * Math.PI;
  }
}

圆锥不是圆的正确子类,圆锥应该有一个字段Circle baseShape

答案 1 :(得分:1)

此处变量区域是一个实例变量,因此它的默认值设置为0.0d。请参阅此link。如果要更改区域值,则要调用 getArea()方法。检查以下代码,

public double getVolume() {
      return (getArea()* height / 3)
}

答案 2 :(得分:0)

您正在使用protected完全可以将变量继承到子类。这是正确的答案

//SUPERCLASS
public class Circle {

  protected double radius;
  protected double area;

  //Some code to construct object and initialize radius

  //Return Calculated Area
  protected double getArea() {
    area = Math.pow(radius, 2) * Math.PI;
    return area;
  }

}

//SUBCLASS
public class Cone extends Circle {

  private double height;

//Some more code with constructors and different methods

  public double getVolume() {
    {
      return (getArea() * height / 3)
    }
  }

答案 3 :(得分:0)

除非您将值设置为半径和面积,否则它将保持为0.我假设您已设置该值。您应该使用关键字来获取设定值。如果你把整个代码放在一起而不仅仅是将它隐藏为注释,那么很容易找到这个漏洞。

答案 4 :(得分:0)

为超类和子类添加构造函数,如下所示。

//Super Class
public class Circle {

  protected double radius;
  protected double area;

  public Circle(double radius) {
    this.radius = radius;
    this.area = getArea();
  }

  protected double getArea() {
    area = Math.pow(radius, 2) * Math.PI;
    return area;
  }
}

//Sub Class
public class Cone extends Circle {

private double height;

public Cone(double radius, double height) {
    super(radius);
    this.height = height;
}

public double getVolume() {
    {
      return (area * height / 3);
    }
  }
}

之后,您可以使用 getVolume()子类的方法。

public class Test {

  public static void main(String[] args) {
    Cone c = new Cone(3.0,5.0);
    System.out.println(c.getVolume());
  }
}