方法重写规则:

1.子类要重写的方法与父类方法具有完全相同的返回类型+方法名称+参数列表;

2.子类要重写的方法的访问权限大于或者等于父类方法的访问权限;

3.子类要重写的方法不能抛出比父类方法更大的异常;

circle.class

 1 public class Circle {  
 2 
 3            protected double radius;    
 4 
 5     public Circle(double r) {  
 6              radius=r;
 7     }
 8 
 9     public void setr(double radius){  
10              this.radius=radius;
11      }    
12 
13      public double getr(){
14              return radius;
15      }    
16 
17      public double getarea() {
18              return 3.14*radius*radius;
19      }
20 }

Cylinder.calss

public class Cylinder extends Circle {  

          private double length;    

    public Cylinder() {   
         super(1);                   
         length=1;  
     }

    public void setl(double length){  
          this.length=length;
     }    

     public double getl(){
           return length;  
      }    

        //子类方法对父类getarea方法的重写,获取圆柱表面积    

      public double getarea() {  
            return super.getarea()*2+radius*2*3.14*length;      //在父类中,radius是protected属性,可在子类中直接调用;如果属性为private,则通过getr()获取
      }        

      public double getv(){  
             return super.getarea()*length;   //在子类的方法中使用super.被重写的父类方法对该方法进行调用  
     } 
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-24
  • 2021-12-24
  • 2022-12-23
  • 2022-01-09
  • 2021-11-26
  • 2021-06-09
猜你喜欢
  • 2021-09-08
  • 2021-10-12
  • 2021-07-24
  • 2021-05-23
  • 2022-01-19
  • 2022-12-23
  • 2022-03-05
相关资源
相似解决方案