1 public class Findareas{ 2 public static void main (String []agrs){ 3 Figure f= new Figure(10 , 10); 4 Rectangle r= new Rectangle(9 , 5); 5 Figure figref; 6 figref=f; 7 System.out.println("Area is :"+figref.area()); 8 figref=r; 9 System.out.println("Area is :"+figref.area()); 10 } 11 } 12 class Figure{ 13 double dim1; 14 double dim2; 15 Figure(double a , double b) { 16 dim1=a; 17 dim2=b; 18 } 19 Double area() { 20 System.out.println("Inside area for figure."); 21 return(dim1*dim2); 22 } 23 } 24 class Rectangle extends Figure { //继承Figure父类 25 Rectangle(double a, double b) { 26 super(a ,b); //super调用父类构造方法
27 } 28 Double area() { 29 System.out.println("Inside area for rectangle."); 30 return(dim1*dim2); 31 } 32 }
输出结果如下:
Inside area for figure. Area is :100.0 Inside area for rectangle. Area is :45.0