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

 时间:2024-10-11 19:30:35

java中抽象类作用:

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

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

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

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

首先写一个抽象类shape,他包含一个抽象方法getArea()java抽象类:[1]抽象类shape

从shape类派生出circle类,并用了getArea()计算圆的面积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;

}

}

  • 树莓派用Python点亮LED灯、树莓派硬件控制入门
  • 如何使用WinSQL查看数据库表状态信息
  • java如何读取硬盘里面文件的内容
  • android studio初始化配置
  • 如何在Choregraphe中从零开始创建动作?
  • 热门搜索
    浙江农家乐旅游 辽宁兴城旅游 新西兰旅游地图 春天哪里旅游好 旅游攻略游记 南普陀寺旅游攻略 鸟巢水立方旅游攻略 福州有哪些旅游景点 同程旅游招聘 海南旅游景点介绍