Java 上机----实训操作15---类 体现多态性

定义抽象类Shape,抽象方法为showArea(),求出面积并输出。
定义矩形类Rectangle,正方形类Square,圆类 Circle。根据各自的属性,用showArea方法求出各自的面积。
在main方法中构造3个对象,调用showArea方法。

执行代码:

package chengxu2;
abstract class Shape{
    protected double area;
    abstract void showArea();
}
class Rectangle extends Shape{
    private double x,y;
     protected Rectangle(){}
    Rectangle(double x,double y){
        this.x=x;
        this.y=y;
    }
    public double getX(){
        return x;
    }
    public double getY(){
        return y;
    }
    public void showArea(){
        area=getX()*getY();
        System.out.println(area);
    }
}
class Square extends Shape{
    private double x;
    protected Square(){}
    Square(double x){
        this.x=x;
    }
    public double getX(){
        return x;
    }
    public void showArea(){
        area=getX()*getX();
        System.out.println(area);
    }
}
class Circle extends Shape{
    private double r;
    protected Circle(){}
    Circle(double r){
        this.r=r;
    }
    public double getR(){
        return r;
    }
    public void showArea(){
        area=Math.PI*getR()*getR();
        System.out.println(area);
    }
}
public class test2 {
    public static void main(String args[]){
        Shape r=new Rectangle(4,5);
        fun(r);
        Shape s=new Square(4);
        fun(s);
        Shape c=new Circle(4);
        fun(c);
    }
    public static void fun(Shape p){
        p.showArea();
    }
}

执行结果:

在这里插入图片描述

·先调试后运行

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

软件程序媛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值