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