1 //抽象类示例: 2 abstract class Shape1 3 { 4 { 5 System.out.println("执行Shape的初始化块..."); 6 } 7 private String color; 8 //定义一个计算周长的抽象方法, 9 public abstract double calPerimeter(); 10 //定义一个返回形状的抽象方法, 11 public abstract String getType(); 12 //定义Shape的构造器,该构造器并不是用于创建Shape对象,而是用于创建子类调用 13 public Shape1(){} 14 public Shape1(String color) 15 { 16 System.out.println("执行Shape的构造器..."); 17 this.color = color; 18 } 19 public void setColor(String color){this.color = color;} 20 public String getColor(){return color;} 21 } 22 23 class Triangle extends Shape1 24 { 25 //定义三角形的三边 26 private double a; 27 private double b; 28 private double c; 29 public Triangle(String color,double a,double b,double c) 30 { 31 super(color); 32 this.setSides(a,b,c); 33 } 34 public void setSides(double a,double b,double c) 35 { 36 if(a>b+c || b>a+c || c>a+b) 37 { 38 System.out.println("三角形两边之和必须大于第三边"); 39 return; 40 } 41 this.a = a; 42 this.b = b; 43 this.c = c; 44 } 45 //重写Shape类的计算周长的抽象的方法 46 public double calPerimeter() 47 { 48 return a+b+c; 49 } 50 //重写Shape类的返回形状的抽象的方法 51 public String getType() 52 { 53 return "三角形"; 54 } 55 } 56 57 public class AbstractTest 58 { 59 public static void main(String[] args) 60 { 61 Shape1 s1 = new Triangle("黑色",3,4,5); 62 System.out.println(s1.getType()); 63 System.out.println(s1.calPerimeter()); 64 } 65 }
1 //抽象类的作用;模板作用(本例中: 2 //抽象的父类中,父类的普通方法依赖于一个抽象方法,而抽象方法则推迟到子类中 3 //去实现) 4 abstract class SpeedMeter 5 { 6 private double turnRate; 7 public SpeedMeter(){} 8 public abstract double getRadius(); 9 public void setTurnRate(double turnRate) 10 { 11 this.turnRate = turnRate; 12 } 13 //定义计算速度的方法 14 public double getSpeed() 15 { 16 //速度等于车轮半径*2*PI*转速 17 return java.lang.Math.PI * 2 * getRadius() * turnRate; 18 } 19 } 20 public class CarSpeedMeter extends SpeedMeter 21 { 22 public double getRadius() 23 { 24 return 0.28; 25 } 26 public static void main(String[] args) 27 { 28 CarSpeedMeter csm = new CarSpeedMeter(); 29 csm.setTurnRate(15); 30 System.out.println(csm.getSpeed()); 31 } 32 }