我的java学习-多态和继承

本文通过实例演示了Java中多态的概念,展示了如何通过继承抽象类Shape并重写getArea方法来实现不同形状面积的计算。涉及Circle、Rectangle、Triangle和Ladder等类的定义及使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一直以来,我都以为java的多态主要表现在由于方法所自带的参数,类型不同,数目多少不同而带来的同名称方法的重用。
原来还有对抽象类方法的继承和重写,也是多态的一种表现。
下面的代码里面,几个类class都是继承了Shape类,同时重写了里面的getArea方法,也是一种多态的表现。

abstract class Shape {
public abstract double getArea();
}

class Circle extends Shape{
    private double r;
    public Circle(double r){
        this.r = r;
    }
    public double getArea(){
        return 3.14 * r * r;
    }
}
class Rectangle extends Shape{
    private double a, b;
    public Rectangle(double a, double b){
        this.a = a;
        this.b = b;
    }
    public double getArea(){
        return a * b;
    }
}
class Triangle extends Shape{
    private double a, b, c;
    public Triangle(double a, double b, double c){
        this.a = a;
        this.b = b;
        this.c = c;
    }
    public double getArea(){
        double temp = 0.5 * (a + b + c);
        return Math.sqrt(temp * (temp -a) * (temp -b) *(temp -c));
    }
}
class Ladder extends Shape{
     private double a, b, h;
    public Ladder(double a, double b, double h){
        this.a = a;
        this.b = b;
        this.h = h;
    }
    public double getArea(){        
        return 0.5 * (a + b) * h;
    }
}

public class Test2{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        
        System.out.println("请输入圆的半径:");
        double r = sc.nextDouble();
        Shape area1 = new Circle(r);
        System.out.println("圆的面积是:" + area1.getArea());
        
        System.out.println("请输入矩形的两条边长,回车键分隔:");
        double a1 = sc.nextDouble();
        double a2 = sc.nextDouble();
        Shape area2 = new Rectangle(a1, a2);
        System.out.println("矩形的面积是" + area2.getArea());
        
        System.out.println("请输入梯形的上下边长和高,回车键分隔:");
        double b1 = sc.nextDouble();
        double b2 = sc.nextDouble();
        double b3 = sc.nextDouble();
        Shape area3 = new Ladder(b1, b2, b3);
        System.out.println("梯形的面积是:" + area3.getArea());
        
        System.out.println("请输入三角形的三条边,回车键分隔:");
        double c1 = sc.nextDouble();
        double c2 = sc.nextDouble();
        double c3 = sc.nextDouble();
        Shape area4 = new Triangle(c1, c2, c3);
        System.out.println("三角形的面积是:" + area4.getArea());
        
        double area = area1.getArea() + area2.getArea() +
                area3.getArea() + area4.getArea();
        System.out.println("几个图形面积的和是:" + area);
    }    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值