您的位置:首页 > 编程语言 > Java开发

Java + 面向抽象abstract类与函数实现(计算三角形、圆形的面积)

2016-10-03 23:19 603 查看
本次进行面向抽象abstract类与函数实现,其内功能为计算三角形和圆形的面积。

所谓面向抽象编程是指当设计某种重要的类时,不让该类面向具体的类,而是面向抽象类,及所设计类中的重要数据是抽象类声明的对象,而不是具体类声明的对象。就是
利用abstract来设计实现用户需求。

第一步:定义一个抽象类Geometry,类中定义一个抽象的getArea()方法,Geometry类如下。这个抽象类将所有计算面积的方法都抽象为一个标识:getArea()无需考
虑算法细节。

public abstract class Geometry{
public abstract double getArea();
}


当一个非抽象类是某个抽象类(如Geometry)的子类,那么它必须重写父类的抽象方法(如getArea()),给出方法体。

================================================================================================================================

在以下完整测试中

我们会使用到五个类   1.Pillar   2.Geometry   3.Lader   4.Circle   5.Example5_10

.

.

1.Pillar

.

.

.

2. Geometry(抽象类)

.

.

.

3.Lader

.

.

.

4.Circle

.

.

.

5.Example5_10测试类

.

.

================================================================================================================================

.

我们来看一看代码实现

.

.

//柱体Pillar类

package com.ash.www;

public class Pillar{

Geometry bottom;	//将Geometry对象做完成员
double height;		//高

Pillar(Geometry bottom, double height){	//定义构造函数
this.bottom = bottom;
this.height = height;
}
void changeBottom(Geometry bottom){
this.bottom = bottom;
}
public double getVolume(){
return bottom.getArea() * height;
}
}


.

.

.

//几何Geometry类(抽象类)

package com.ash.www;

public abstract class Geometry {

public abstract double getArea();

}
.

.

.

//梯形Lader类

package com.ash.www;

public class Lader extends Geometry{	//继承抽象类Geometry
double a, b, h;

Lader(double a, double b, double h){
this.a = a;
this.b = b;
this.h = h;
}
public double getArea(){
return (1 / 2.0) * (a + b) * h;
}

}


.

.

.

//圆形Circle类

package com.ash.www;

public class Circle extends Geometry{	//继承抽象类Geometry
double r;

Circle(double r){
this.r = r;
}
public double getArea(){
return (3.14 * r * r);
}

}
.

.

.

//Example5_10测试类

package com.ash.www;

public class Example5_10 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Pillar pillar;
Geometry tuxing;

tuxing = new Lader(12, 2
a73e
2, 100);	//tuxing作为Lader对象的引用
System.out.println("Lader area :"+ tuxing.getArea());

pillar = new Pillar(tuxing, 58);
System.out.println("Ladered pillar area :"+ pillar.getVolume());

tuxing = new Circle(10);	//tuxing作为Circle对象的引用
System.out.println("When radius = 10, the circle area :"+ tuxing.getArea());

pillar.changeBottom(tuxing);
System.out.println("Circled pillar area :"+ pillar.getVolume());

}

}
.
.

.

.

看完这篇文章,你是否对面向抽象abstract类与函数实现又有了更深的了解呢?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐