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

作者:神奇的周 | 创建时间: 2023-06-16
java抽象类:[1]抽象类shape

操作方法

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

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

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

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

实例化对象,并调用方法

结果

以下为完整代码 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; } }

点击展开全文

更多推荐