抽象类继承

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());
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值