概述
定义 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 Test {
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);
}
}
Linux
Linux
zha***ixinwe@163.com2年前 (2018-08-28)
最后
以上就是伶俐小虾米为你收集整理的python和java抽象类_Java 抽象类的全部内容,希望文章能够帮你解决python和java抽象类_Java 抽象类所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复