【问题标题】:Printing out return value from a method从方法中打印出返回值
【发布时间】:2018-04-29 10:09:53
【问题描述】:

我正在学习 Java,并且正在学习继承。但我不知道如何打印出方法的返回值。

我有 Circle.java 超类

public class Circle 
{
    private double radius;
    public Circle()
    {
        radius = 1.0;
    }
    public double getRadius()
    {
    return radius;
    }
    public void setRadius( double r )
    {
        radius = r;
    }
    public double findArea()
    {
        return Math.pow(radius ,  2)*Math.PI;
    }   
}

和 Cylinder.java 子类

public class Cylinder extends Circle
{
    private double height;
    public Cylinder()
    {
        super();
        height = 1.0;
    }
    public void setHeight( double h )
    {
        height = h;
    }
    public double getHeight()
    {
        return height;
    }
    public double findVolume()
    {
        return findArea() * height;
    }
}

但是当我在 Cylinder 子类中添加主要方法和 System.out.println(findVolume()) 时,我得到“无法从类型 Cylinder 对非静态方法 findVolume() 进行静态引用”。任何帮助都会很棒

【问题讨论】:

    标签: java inheritance return


    【解决方案1】:

    main 方法中,您在类范围内,而不是在实例范围内。为了访问实例方法,您需要对类的实例进行操作:

    public static void main(String[] args) {
       Cylinder cylinder = new Cylinder();
       cylinder.setHeight(10);
       cylinder.setRadius(30);
       System.out.println(cylinder.findVolume());
    }
    

    【讨论】:

      【解决方案2】:

      这与继承无关。

      错误信息很清楚。 main 方法是静态的,findVolume 不是静态的,不能直接从静态方法引用非静态方法。

      相反,您应该创建Cylinder 的实例并在此实例上调用findVolume

      Cylinder cylinder = new Cylinder();
      // set values
      System.out.println(cylinder.findVolume())
      

      【讨论】:

        【解决方案3】:

        那是因为 main 方法是静态的。 您尝试在不创建实例的情况下调用对象方法。

        它应该是这样工作的:

        public static void main(String[] args){
            Cylinder cylinder = new Cylinder();
        
            System.out.println(cylinder.findVolume());
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-09-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-01
          • 1970-01-01
          相关资源
          最近更新 更多