Java编程基础篇之多态性
通过继承和重载的结合,超类可以定义供他所有子类可以使用方法的通用形式。如下代码:
class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } double GetArea() { System.out.println("The figure is undefined!"); return 0; } } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } double GetArea() { System.out.println("this is in Rectangle."); return dim1 * dim2; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } double GetArea() { System.out.println("this is in Triangle."); return dim1 * dim2/2; } } public class HelloWorld { public static void main(String[] args) { Figure f = new Figure(1, 2); Rectangle r = new Rectangle(3, 4); Triangle t = new Triangle(5, 6); Figure area; area = f; System.out.println("area = " + area.GetArea()); area = r; System.out.println("area = " + area.GetArea()); area = t; System.out.println("area = " + area.GetArea()); } }
运行结果:
The figure is undefined! area = 0.0 this is in Rectangle. area = 12.0 this is in Triangle. area = 15.0
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。