您的位置:首页 > 编程语言 > Java开发

java学习日志(三)---实验2

2017-03-23 15:16 399 查看
题目:(1)编写一抽象类(shape),长方形类、三角形类与圆类均为其子类,并各有各的属性。其中父类有获得其周长、面积的方法。然后在一测试类中,分别建立若干个子对象,并分别将这些对象的面积与周长统计输出。

(2)在上述基础上,编写锥体,包括下底和高,求下底分别为长方形,三角形,圆形的椎体体积。

public abstract class Shape
{
public abstract double getPerimeter();
public abstract double getArea();
}
public class Rectangle extends Shape
{
double a,b;
Rectangle(double a,double b){
this.a=a;
this.b=b;
}
public double getPerimeter(){
return 2*a*b;
}
public double getArea(){
return a*b;
}
}
public class Circle extends Shape
{
double r;
Circle(double r){
this.r=r;
}
public double getPerimeter(){
return 2*3.14*r;
}
public double getArea(){
return 3.12*r*r;
}
}
import java.lang.Math;

public class Triangle extends Shape
{
double a,b,c,d;
Triangle(double a,double b,double c){
this.a=a;
this.b=b;
this.c=c;
}
public double getPerimeter(){
return a+b+c;
}
public double getArea(){
return Math.sqrt(a*a+b*b)*c*0.5;
}
}
public class Pyramis
{
Shape bottom;
double height;
Pyramis(Shape bottom,double height){
this.bottom=bottom;
this.height=height;
}
public double getVolume(){
return bottom.getArea()*height*1/3;
}
}
public class Application
{
public static void main(String[] args)
{
Pyramis pyramis;
Shape shape1=new Rectangle(3,4);
pyramis=new Pyramis(shape1,3);
System.out.println("矩形的周长为:"+shape1.getPerimeter());
System.out.println("矩形的面积为:"+shape1.getArea());
System.out.println("四棱锥的体积为:"+pyramis.getVolume());
System.out.println();

Shape shape2=new Circle(4);
pyramis=new Pyramis(shape2,3);
System.out.println("圆的周长为:"+shape2.getPerimeter());
System.out.println("圆的面积为:"+shape2.getArea());
System.out.println("圆锥的体积为:"+pyramis.getVolume());
System.out.println();

Shape shape3=new Triangle(3,4,5);
pyramis=new Pyramis(shape3,3);
System.out.println("三角形的周长为:"+shape3.getPerimeter());
System.out.println("三角形的面积为:"+shape3.getArea());
System.out.println("三角锥的体积为:"+pyramis.getVolume());
System.out.println();
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: