面向抽象编程

/*	
 * 面相抽象编程
 *使用对台进行编程的核心技术之是使用上转型对象,即将abstract 类生命对象作为一个子类的上转对象,那么这个上转对象就可以调用子类重的方法,
 *所谓面向抽象编程,是指设计一个类时,不让该类面向具体的类,而是面向一个抽象的类,即所设计类中的重要数据是抽象类声明的对象,而不是具体类声明的对象。
 */
//通过面向抽象来设计Pillar类,使得该类不依赖具体类,因此每当系统增加新的Geometry的子类的时候,如增加一个Triangle子类,就不用再修改Pillar类的任何代码,就可以使用Pillar创建出具有三角形低的柱体
public abstract class Geometry
{
	public abstract double getArea();
}
public class Pillar{//设计一个类使其面向一个抽象的类,而不是具体的类,
	Geometry bottom;//抽象类Geometry声明的对象(类中的数据是抽象类生命的对象)
	double height;
	Pillar (Geometry bottom,double height){
		this.bottom=bottom;
		this.height=height;
	}
	public double getVolume(){
		return bottom.getArea()*height;//bottom可以调用子类重写的getArea()方法。
	}	
}
//下列Circle和Rectangle 类都是Gmometry的子类,二者都必须重写getArea()方法,来计算各自的面积
//Circle.java
public class Circle extends Geometry{
	double r;
	Circle(int r){
		this.r=r;
	}
	public double getArea(){
		return 3.14*r*r;
	}
}
//Rectangle.java
public class Rectangle extends Geometey{
	double a,b;
	Rectangle(double a,double b){
		this.a=a;
		this.b=b;
	}
	public class getArea(){
		return a*b;
	}
}
//APPlication.java
public class Application{
	public static void main(String[] args){
		Pillar pillar;
		Geometry bottom;
		bottom=new Rectangle(12,22);//上转型对象
		pillar=new Pillar(bottom,58);//pillar是具有矩形底的柱体
		System.out.println("矩形体的主体体积"+pillar.getVolume());
		bottom=new Circle(10);
		pillar=new Pillar(bottom,58);
		System.out.println("圆形体的主体体积:"+pillar.getVolume());
	}
}

/*开-闭原则
 * 就是让设计的系统对扩展开放,对修改关闭
 * 本质就是当系统中增加模块的时候,不需要修改现有的模块。
 * 再设计系统时,首先考虑到用户需求的变化,将对用户变化的部分设计为对扩展开放,而设计的核心部分是指经过精心考虑之后确定的基本结构,这部分对修改是关闭的,既不能因为用户需求的变化而发生改变,因为这部分不是用来应对需求变化的。
 * 如果系统遵守了开-闭原则,那么系统一定是利于维护的。
 */
//设计一格 动物模拟器,希望设计的模拟器可以模拟很多动物的声音
//Animal.java
public abstract class Animal{
	public abstract  void cry();
	public abstract String getAnimalNmae();
}
//Simulator.java
public class Simulator{
	public void palySound(Animal animal){
		System.out.println("现在播放"+animal.getAnimalNmae()+"类的声音: ");
		animal.cry();
	}
}
//dog.java
public class Dog extends Animal{
	public void cry(){
		System.out.println("wang...wang");
	}
	public String getAnimalName(){
		return "dog";
	}
}
//cat.java
public class Cat extends Animal{
	public void cry(){
		System.out.println("meo..meo");
	}
	public String getAnimalName(){
		return "cat";
	}
}
public class Application{
	public static void main(String[] args){
		Simulator simulator=new Simulator();
		simulator.playSound(new Dog());
		simulator.playSound(new Cat());
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值