java的抽象类的三角形周长_怎么使用Java把抽象类改为接口计算三角形,长方形,圆形的面积?...

可以写一下详细过程吗?

interface Graphices {

// 计算面积的抽象方法,分号";"必不可少

public abstract double area();

}

abstract class PlaneGraphics {

protected String shape; // 形状

// 构造方法,将形状类型字符串赋予变量shape

public PlaneGraphics(String shape) {

this.shape = shape;

}

// 无参构造方法,图形类型为"未知图形"

public PlaneGraphics() {

this("未知图形");

}

public void print() {

}

}

// 设计长方形类Rectangle,继承平面图形类并实现图形接口

class Rectangle extends PlaneGraphics implements Graphices {

protected double length; // 长度

protected double width; // 宽度

// 长方形构造方法

public Rectangle(double length, double width) {

super("长方形");

this.length = length;

this.width = width;

}

// 正方形构造方法,正方形是长方形的特例

public Rectangle(double width) {

super("正方形");

this.length = width;

this.width = width;

}

// 无参构造方法,将length和width均赋0,此时图形形状为"未知图形"

public Rectangle() {

}

// 计算长方形面积,实现父类的抽象方法

public double area() {

return width * length;

}

public void print() {

System.out.println(shape + "面积为 " + this.area());

}

}

// 设计椭圆类Eclipse,继承平面图形类并实现图形接口

class Eclipse extends PlaneGraphics implements Graphices {

protected double radius_a; // a轴半径

protected double radius_b; // b轴半径

// 椭圆构造方法

public Eclipse(double radius_a, double radius_b) {

super("椭圆");

this.radius_a = radius_a;

this.radius_b = radius_b;

}

// 圆构造方法,圆是椭圆的特例

public Eclipse(double radius_a) {

super("圆");

this.radius_a = radius_a;

this.radius_b = radius_a;

}

// 无参构造方法,将radius_a和radius_b均赋0,此时图形形状为"未知图形"

public Eclipse() {

}

// 计算椭圆的面积,实现父类的抽象方法

public double area() {

return Math.PI * radius_a * radius_b;

}

public void print() {

System.out.println(shape + "面积为 " + this.area());

}

}

// 设计三角形类Triangle,继承平面图形类并实现图形接口

class Triangle extends PlaneGraphics implements Graphices {

protected double bottom;

protected double height;

Triangle(double bottom, double height) {

super("三角形");

this.bottom = bottom;

this.height = height;

}

public double area() {

return 0.5 * bottom * height;

}

public void print() {

System.out.println(shape + "面积为 " + this.area());

}

}

public class PlaneGraphics_ex {

public static void main(String[] args) {

// 获得长方形子类实例

PlaneGraphics g = new Rectangle(10, 20);

// 调用抽象类中的print()方法

g.print();

g = new Eclipse(10, 20); // 椭圆

g.print();

g = new Triangle(10, 20);//三角形

g.print();

}

}

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值