abstract class Type { //创建一个抽象类Type
//声明数据成员
double height, width, length; //长,宽,高
String name; //名字
//定义抽象方法
abstract double area(); //面积()
abstract String getName(); //获取名字()
public Type(double heigth, double width) { //抽象类的构造方法
this.height = heigth;
this.width = width;
}
public Type(double heigth, double width, double length) {//抽象类的构造方法
this.height = heigth;
this.width = width;
this.length = length;
}
public void setName(String name) { //给抽象类的name属性赋值
this.name = name;
}
}
class Triangle extends Type { //创建一个三角形的子类继承抽象类
public Triangle(double height, double width) { //给抽象类的数据成员赋初值
super(height, width);
}
double area() { //三角形的面积公式
return height * width / 2;
}
String getName() { //获取名字()
return name;
}
}
class Trapezoidal extends Type { //创建一个梯形的子类继承抽象类
public Trapezoidal(double height, double width, double length) {//给抽象类的数据成员赋初值
super(height, width, length);
}
double area() { //梯形的面积公式
return (height + width) * length / 2;
}
String getName() { //获取名字()
return name;
}
}
public class AbstractTest {
public static void main(String[] args) {
Triangle t = new Triangle(23, 2); //创建Triangle类的对象并初始化
Trapezoidal tz = new Trapezoidal(12, 34, 2); //创建Trapezoidal类的对象并初始化
t.setName("三角形的面积");
tz.setName("梯形的面积");
System.out.println(t.getName() + " " + t.area());
System.out.println(tz.getName() + " " + tz.area());
}
}
抽象类继承
最新推荐文章于 2021-09-06 16:09:11 发布