学习交流

当前位置 /首页/母婴教育/学习交流/列表

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

操作方法

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

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

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

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

java抽象类:[1]抽象类shape 第2张

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

java抽象类:[1]抽象类shape 第3张

(05)实例化对象,并调用方法

(06)结果

java抽象类:[1]抽象类shape 第4张

(07)以下为完整代码public class demo3 {public static void main(String[] args) {rectang rec=new rectang(3,5);tln("Area for Circle with width=3 and height=5 is:"+rea());circle cir=new circle(2);tln("Area for Circle with r=2 is:"+rea());}}abstract class shape{public abstract double getArea();}class rectang extends shape{private double width;private double height;public rectang(double width,double height){h=width;ht=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 *r*r;}}

TAG标签:抽象类 JAVA shape #