首页 > 解决方案 > 从方法中打印出返回值

问题描述

我正在学习 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() 进行静态引用”。任何帮助都会很棒

标签: javainheritancereturn

解决方案


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

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

推荐阅读