Java思想之什么是面向抽象?abstract类实现(计算三角形、圆形的面积)

本次进行面向抽象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测试类

 

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

 

我们来看一看代码实现

 

//柱体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, 22, 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类与函数实现又有了更深的了解呢?



 

 

 

 

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值