java 求体积

Python016

java 求体积,第1张

在main方法中实现Shape的对象时,使用Trangle或者Rectangle分别进行实例化。这样对于同一个Pillar的对象,可以调用两个不同类的实现方法来计算。具体代码请参考下面。

Shape.java

public abstract class Shape {

public int dim1

public int dim2

public abstract int getArea()

}

Trangle.java

public class Trangle extends Shape {

public int getArea() {

return (super.dim1 * super.dim2) / 2

}

}

Rectangle.java

public class Rectangle extends Shape {

public int getArea() {

return super.dim1 * super.dim2

}

}

Pillar.java

public class Pillar {

public Shape shape

public int height

public int getVolumn() {

return this.shape.getArea() * this.height

}

public static void main(String[] args) {

// 三棱柱

Pillar p = new Pillar()

p.shape = new Trangle()

p.shape.dim1 = 2

p.shape.dim2 = 4

p.height = 3

System.out.println("三棱柱的体积是:" + p.getVolumn())

// 四棱柱

p.shape = new Rectangle()

p.shape.dim1 = 2

p.shape.dim2 = 4

p.height = 3

System.out.println("四棱柱的体积是:" + p.getVolumn())

}

}

下面是执行后的结果:

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)

}

}

我直接给你写一个吧

public class ChangFangTi{

private double chang

private double kuan

private double gao

public ChangFangTi(){}

public ChangFangTi(double chang,double kuan,double gao){

this.chang = chang

this.kuan = kuan

this.gao = gao

}

public void setChang(double chang){

this.chang = chang

}

public double getChang(){

return this.chang

}

public void setKuan(double kuan){

this.kuan = kuan

}

public double getKuan(){

return this.kuan

}

public void setGao(double gao){

this.gao = gao

}

public double getGao(){

return this.gao

}

public double mianji(){

return chang * kuan * gao

}

public static void main(String [] args){

ChangFangTi cft = new ChangFangTi(2,3,5)

System.out.println("长方体的体积是:" + cft.mianji())

}

}