1、定义一个抽象类Shape,类中封装属性name指定图形名称,定义用于求面积的抽象方法。定义3个子类:圆形类Circle、梯形类Trapezoid和三角形类Triangle,都继承Shape类,子类中各自新增属性,定义构造方法、设置属性值的方法并重写shape类中的方法。在Circle类和Triangle类中还新增求周长的方法。在主类中定义Shape类的对象,创建子类对象,设置其属性值,并输出其面积与周长,在程序中要体现上转型对象的使用。
源代码:
MainClass类:
package demo03;
public class MainClass {
public static void main(String[] args) {
Shape shape = new Shape();
Circle circle = new Circle();
//设置圆的各个属性
circle.setName("circle");
circle.setRadius(4);
//输出圆的面积和周长
circle.area(circle.getRadius());
circle.circumference(circle.getRadius());
//初始、创建trapezoid对象设置trapezoid的各个属性
Trapezoid trapezoid = new Trapezoid(6,8,5,10,12);
trapezoid.setName("trapezoid");
//输出梯形的面积和周长
trapezoid.area(trapezoid.above, trapezoid.button,trapezoid.height);
System.out.println("梯形的周长为:"+trapezoid.circumference(trapezoid.above,
trapezoid.button,trapezoid.left,trapezoid.right));
//初始、创建triangle对象设置triangle的各个属性
Triangle triangle = new Triangle(8,8);
triangle.setName("triangle");
//三角形面积
triangle.area(triangle.a, triangle.b);
}
}
Shape:
package demo03;
public class Shape {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void area(double ... a){
System.out.println("面积为"+a);
}
}
Circle类:
package demo03;
public class Circle extends Shape{
private double radius;//定义圆的半径
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
//重写方法,计算圆的面积
@Override
public void area(double... a) {
System.out.println("圆的面积为:"+a[0]*a[0]*3.14);
}
//求圆的周长
public void circumference(double radius){
System.out.println("圆的周长为:"+2*3.14*(radius));
}
public Circle() {
}
}
Trapezoid:
package demo03;
public class Trapezoid extends Shape{
double above;//定义梯形的上底
double button;//定义梯形的下底
double height;//定义梯形的高
double left;//定义梯形的左腰
double right;//定义梯形的右腰
public Trapezoid(double above, double button, double height, double left, double right) {
this.above = above;
this.button = button;
this.height = height;
this.left = left;
this.right = right;
}
//重写面积方法
@Override
public void area(double... a) {
System.out.println("梯形的面积为:"+(a[0]+a[1])*a[2]/2);
}
//计算梯形周长
public double circumference(double a,double b,double c,double d){
return a+b+c+d;
}
}
Triangle类:
package demo03;
import javax.swing.plaf.synth.SynthOptionPaneUI;
public class Triangle extends Shape{
double a;//定义三角形的底
double b;//定义三角形的高
//重写面积方法
@Override
public void area(double... a) {
System.out.println("三角形的面积为:"+a[0]*a[1]/2);
}
public Triangle(double a, double b) {
this.a = a;
this.b = b;
}
}
实验运行截图: