程序示例:
class Grap{ public Double getArea(){ return 0.0; }}class Circle extends Grap{ private Integer r; //半径 Circle(Integer r) { this.r = r; } public Double getArea(){ return 3.14*r*r; }}class Equals extends Grap{ private Integer x; //长 private Integer y; //宽 Equals(Integer x,Integer y) { this.x = x; this.y = y; } public Double getArea(){ return x*y.doubleValue(); }}public class UnAbstract { public static void main(String[] args) { System.out.println(new Circle(10).getArea()); System.out.println(new Equals(10,10).getArea()); }}
程序示例运行结果:
314.0100.0
如何解决上述问题? 抽象!
抽象方法 抽象类
程序示例:
abstract class Grap{ abstract public Double getArea(); //抽象方法的类一定是抽象类}class Circle extends Grap{ private Integer r; //半径 Circle(Integer r) { this.r = r; } public Double getArea(){ return 3.14*r*r; }}// 抽象类的继承类为非抽象类时必须重新父类的抽象方法。abstract class Equals extends Grap{ private Integer x; //长 private Integer y; //宽 Equals(Integer x,Integer y) { this.x = x; this.y = y; } }public class UnAbstract { public static void main(String[] args) { System.out.println(new Circle(10).getArea()); }}
程序示例运行结果:
314.0