java - 从方法中打印出返回值
问题描述
我正在学习 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() 进行静态引用”。任何帮助都会很棒
解决方案
在main
方法中,您在类范围内,而不是在实例范围内。为了访问实例方法,您需要对类的实例进行操作:
public static void main(String[] args) {
Cylinder cylinder = new Cylinder();
cylinder.setHeight(10);
cylinder.setRadius(30);
System.out.println(cylinder.findVolume());
}
推荐阅读
- javascript - 说如果在javascript中保持30分钟
- outlook - EWS:如何从 Outlook 获取 CRM ID?
- java - 尝试制作 group.toList() 但看起来有问题。但是得到了:只允许一个订阅者!如何修复代码?
- hyperledger-fabric - Hyperledger Fabric:无法更新排序服务端点,因为找不到带有 mychannel id 的通道
- python - 无法在 Python 中提取加密的 Zip 文件
- php - Laravel 5.5:使用 Join 和 Where 子句构建查询
- python - 缺少模块“awx.main.db”
- c++ - 在 C++ 中用 lambda 替换函数
- sql - 在 bigquery 的 2 列中拆分一行
- javascript - 需要从 Chrome 开发工具捕获性能监视器详细信息到 Java 程序中