原文地址:
http://www.5ixiudou.com/portal/detailInfo/1000000005/217
抽象,是指把一些不同类型的物体的共有属性或者行为抽取出来,然后构成一个公共的父类。然后当使用这些公共的属性或者行为的使用,就可以通过父类去调用,这样的话,就不用去考虑具体应该由谁去调用这个行为,屏蔽了类型的细节,用起来更方便。废话不多说,直接上代码:
package cn.cttic.staffcert.cert.service;
//定义形状类
public abstract class Graphics {
//计算面积
public abstract double getGirth(Graphics g);
public static void main(String[] args) {
//注意,在使用时,要先向上类型转换,然后父类对象进行调用时,自动调用相应子类类型的方法
//计算三角形面积
Graphics g = new Triangle (3,4,5);
double area = g.getGirth(g);
System.out.println(area);
//计算圆形面积
Graphics gC = new Circle(2);
double areaC = gC.getGirth(gC);
System.out.println(areaC);
}
}
//定义三角形类,继承自形状类
class Triangle extends Graphics {
public Triangle(float longValue ,float widthValue ,float heightValue){
this.longValue = longValue;
this.widthValue = widthValue;
this.heightValue = heightValue;
}
private float longValue;
private float widthValue;
private float heightValue;
//实现公共方法
@Override
public double getGirth(Graphics g){
return longValue + widthValue + heightValue ;
}
}
//定义圆形类,继承自形状类
class Circle extends Graphics {
private float r;
public Circle (float r){
this.r = r;
}
//实现公共方法
@Override
public double getGirth(Graphics g){
return Math.PI * r * 2 ;
}
}