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

2025-04-15 18:39:18

java中抽象类作用:

通过继承它实现多态,后期绑定,可以为将来要实现的东西做好接口,实现重用性。

要如何使用呢,接下来菀蒯踔观我们来简单实现一下

例:定义一个抽象类shape,他包含一个抽象方法getArea(),从shape类派生出Rectang和

circle类,这两个类都用getArea()方法计算对象的面积

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

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

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

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

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

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

实例化对象,并调用方法

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

结果

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

以下为完整代码

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;

}

}

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢