java实例--每日一练
作者:互联网
方法覆盖
- 方法重载(Overloading):如果有两个方法的方法名相同,但参数不一致,哪么可以说一个方法是另一个方法的重载。
- 方法覆盖(Overriding):如果在子类中定义一个方法,其名称、返回类型及参数签名正好与父类中某个方法的名称、返回类型及参数签名相匹配,那么可以说,子类的方法覆盖了父类的方法。
- Java 方法覆盖(Overriding)代码的实现:
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
标签:java,Figure,area,--,double,实例,println,方法,figref 来源: https://www.cnblogs.com/fshny/p/16136540.html