Java抽象类和抽象方法例子
题目:定义Shape类表示一般二维图形。Shape具有抽象方法area和perimeter,分别计算形状的面积和周长。试定义一些二维形状类(如矩形、三角形、圆形等),这些均为Shape类的子类并计算出这些形状的面积和周长,打印输出相关信息。
代码:
//形状类
public abstract class Shape { public abstract double area(); public abstract double perimeter(); }
//矩形类
public class Rectangle extends Shape { private double length; private double width; public double getLength() { return length; } public void setLength(double length) { this.length = length; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } @Override public double area() { return getLength() * getWidth(); } @Override public double perimeter() { return 2 * (getWidth() + getWidth()); } }
//三角形类
public class Triangle extends Shape { private double a, b, c; public double getA() { return a; } public void setA(double a) { this.a = a; } public double getB() { return b; } public void setB(double b) { this.b = b; } public double getC() { return c; } public void setC(double c) { this.c = c; } @Override public double area() { double p = (getA() + getB() + getC()) / 2; return Math.sqrt(p * (p - getA()) * (p - getB()) * (p - getC())); } @Override public double perimeter() { return getA() + getB() + getC(); } }
//圆形类
public class Circle extends Shape { private double diameter; public double getDiameter() { return diameter; } public void setDiameter(double diameter) { this.diameter = diameter; } @Override public double area() { return Math.PI * Math.pow(getDiameter() / 2, 2); } @Override public double perimeter() { return Math.PI * getDiameter(); } }
//测试代码
public class 测试 { public static void main(String [] args){ Rectangle rec = new Rectangle(); rec.setLength(10); rec.setWidth(5); double rec_area = rec.area(); double rec_perimeter = rec.perimeter(); System.out.println("矩形的面积:"+rec_area+",周长"+rec_perimeter); Triangle tri = new Triangle(); tri.setA(3); tri.setB(4); tri.setC(5); double tri_area = tri.area(); double tri_perimeter = tri.perimeter(); System.out.println("三角形的面积:"+tri_area+",周长"+tri_perimeter); Circle cir = new Circle(); cir.setDiameter(10); double cir_area = cir.area(); double cir_perimeter = cir.perimeter(); System.out.println("圆形的面积:"+cir_area+",周长"+cir_perimeter); } }