用java编写圆锥,java编写圆锥形体积

该博客展示了如何使用Java编程实现抽象类`shape`来定义形状的通用属性,并通过子类`spherosome`(球)和`cone`(圆锥)来覆盖抽象方法计算各自体积。代码中定义了圆球和圆锥的体积计算公式,并在`test`类中进行了实例化和测试。
摘要由CSDN通过智能技术生成

2018-11-22 回答

abstract class shape{

protected static final double pi = 3.14;

abstract double volume();

}

class spherosome extends shape{

private double radius;

public spherosome(double radius){

this.radius = radius;

}

@override

double volume() {

// 圆球的体积公式=(4/3)πr^3

return pi*radius*radius*radius*4/3;

}

}

class cone extends shape{

private double radius, height;

public cone(double radius, double height){

this.radius = radius;

this.height = height;

}

@override

double volume() {

// 圆锥的体积公式=(1/3)hπr^2

return height * pi * radius * radius / 3;

}

}

public class test {

public void testspherosome(double radius){

spherosome spherosome = new spherosome(radius);

system.out.println("圆球的半径:" + radius + ", 圆球的体积:" + spherosome.volume());

}

public void testcone(double radius, double height){

cone cone = new cone(radius, height);

system.out.println("圆锥的底半径:" + radius + ",高:" + height + ", 圆锥的体积:" + cone.volume());

}

public static void main(string[] args) {

test test = new test();

test.testspherosome(1);

test.testcone(1, 1);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值