爱学网
当前位置 : 爱学网 > 经验 > 学习经验 > java抽象类:[1]抽象类shape

java抽象类:[1]抽象类shape

更新时间:2026-05-04 19:24:58

操作方法

01

java中抽象类作用:通过继承它实现多态,后期绑定,可以为将来要实现的东西做好接口,实现重用性。要如何使用呢,接下来我们来简单实现一下例:定义一个抽象类shape,他包含一个抽象方法getArea(),从shape类派生出Rectang和circle类,这两个类都用getArea()方法计算对象的面积

02

首先写一个抽象类shape,他包含一个抽象方法getArea()

03

从shape类派生出rectang类,并用了getArea()计算矩形的面积

04

从shape类派生出circle类,并用了getArea()计算圆的面积

05

实例化对象,并调用方法

06

结果

07

以下为完整代码public class demo3 {public static void main(String[] args) {rectang rec=new rectang(3,5);System.out.println("Area for Circle with width=3 and height=5 is:"+rec.getArea());circle cir=new circle(2);System.out.println("Area for Circle with r=2 is:"+cir.getArea());}}abstract class shape{public abstract double getArea();}class rectang extends shape{private double width;private double height;public rectang(double width,double height){this.width=width;this.height=height;}public double getArea(){return width*height;}}class circle extends shape{private double r;public circle(double radius){this.r=radius;}public double getArea(){return Math.PI*r*r;}}