面向抽象编程

  1. 设计程序时,可以先声明一个抽象类,类中声明若干个抽象方法,表明这些方法在整个系统设计中的重要性,方法体的内容细节由它的非抽象子类去完成。
  2. 利用多态实现编程:核心技术是使用方法重写和上转型对象,即将抽象类声明对象作为其子类的上转型对象,那么这个上转型对象就可以调用子类重写的方法。

没有使用抽象类实例:

class Circle {
    double r;
    Circle(double r) {
        this.r=r;
    }
    public double getArea() {
        return(3.14*r*r);
    }
}
class Pillar {
    double height;
    Circle bottom;
    Pillar (Circle bottom,double height) {
        this.bottom=bottom; 
        this.height=height;
    }
    public double getVolume() {
        if(bottom==null) {
           System.out.println("没有底,无法计算体积");
           return -1;
        }
        return bottom.getArea()*height; 
    }
}
public class Test1{
    public static void main(String args[]){
        Pillar pillar;
        Circle bottom = null;       
        bottom=new Circle(10);
        pillar =new Pillar (bottom,58); 
        System.out.println("体积"+pillar.getVolume());
    }
} 

使用抽象类实例:

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

class Circle extends Geometry{
    double r;
    public Circle(double r) {
        this.r=r;
    }
    public double getArea() {   //实现父类抽象方法
        return(3.14*r*r);
    }
}
class Rectangle extends Geometry{
	double a,b;
	public Rectangle(double a, double b) {
		
		this.a = a;
		this.b = b;
	}
	public double getArea() {  //实现父类抽象方法
        return a*b;
	}

}

class Pillar {   //计算体积
    double height;
    Geometry bottom;
    public Pillar (Geometry bottom,double height) {
        this.bottom=bottom; 
        this.height=height;
    }
    public double getVolume() {
        if(bottom==null) {
           System.out.println("没有底,无法计算体积");
           return -1;
        }
        return bottom.getArea()*height; 
    }
}
public class Test1{
    public static void main(String args[]){
        Pillar pillar; //声明piller对象,但没有实例化
        Geometry bottom = null; //声明Geometry对象  名字为bottom  ,但没有实例化   

        bottom=new Circle(10); //上轉型   
        //子类同之前没有继承Geometry一样 ,Circle bottom = null;       
                                 //bottom=new Circle(10);
        //通过将参数传入构造方法完成实例化
        pillar =new Pillar (bottom,58);   //通过将参数传入构造方法完成实例化
        System.out.println("体积"+pillar.getVolume());
        
        bottom = new Rectangle(1,2);//上轉型
        pillar =new Pillar (bottom,2); 
        System.out.println("体积"+pillar.getVolume());
    }
} 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值