java学习日志(六)-- 抽象类实验

来源:互联网 发布:金灿荣舌战公知哪一期 编辑:程序博客网 时间:2024/06/08 13:56

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

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

abstract class Shape  {public abstract void shapeInfo(); public abstract double getPerimeter();public abstract double getArea();}class Rectangle extends Shape {private double length, wide;Rectangle(double length, double wide){this.length = length;this.wide = wide;}public void shapeInfo(){System.out.println("该长方形长为:" + length + ",宽为:" +wide);System.out.println("周长为" + getPerimeter() + ",面积为" + getArea());}public double getPerimeter(){return 2*(length+wide);}public double getArea(){return length*wide;}}class Triangle extends Shape {private double a, b, c;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(){double p = (a+b+c)/2;return Math.sqrt(p*(p-a)*(p-b)*(p-c));}public void shapeInfo(){System.out.println("该三角形三边长分别为:" + a + "、" + b + "、" + c);System.out.println("周长为"+getPerimeter()+",面积为"+getArea());}}class Circle extends Shape {private double radius;private final double PI = 3.14;Circle(double radius){this.radius = radius;}public double getPerimeter(){return 2*PI*radius;}public double getArea(){return PI*radius*radius;}public void shapeInfo(){System.out.println("该圆半径为:" + radius);System.out.println("周长为"+getPerimeter()+",面积为"+getArea());}}class Cone {private double height;private Shape bottom;private String coneName;Cone(double height, Shape bottom){this.height = height;this.bottom = bottom;coneName = (bottom instanceof Rectangle)? "矩形棱锥":((bottom instanceof Triangle)? "三棱锥":"圆锥");}public double getVolume(){return (height*bottom.getArea())/3;}public void showVolume(){System.out.println("底面积为" + bottom.getArea() + ",高为" + height + "的" + coneName + "体积为" + getVolume());}}class AbstractDemo {public static void main(String[] args){Shape s1 = new Rectangle(3,4);Shape s2 = new Triangle(3,4,5);Shape s3 = new Circle(3);Cone c1 = new Cone(3,s1);Cone c2 = new Cone(3,s2);Cone c3 = new Cone(3,s3);s1.shapeInfo();c1.showVolume();System.out.println("-----------------------");s2.shapeInfo();c2.showVolume();System.out.println("-----------------------");s3.shapeInfo();c3.showVolume();System.out.println("-----------------------");}}





0 0
原创粉丝点击