super关键字

对于子类继承父类,如果将父类方法重写之后想去调用父类方法,

1 public class test  {
2      int age=10;
3 private double radius;
4 public void add(){
5     System.out.println(age);
6 }
7 }
 1 public class Kids extends test{
 2    int age=15;
 3 public int getAge(){//对于重名的属性也可以创建一个get方法用来返回父类的值,
 4     return super.age;
 5 }
 6     @Override
 7     public  void add() {//重写父类方法覆盖
 8         System.out.println("hello");
 9     }
10 public void fatherMethod(){//重新写一个方法,将父类的方法放进来,用super调用,因为main方法是静态(static)方法
11         //不可以在main方法中使用super进行调用,可以创建一个对象然后进行方法调用
12         super.add();
13 }
14 
15     public static void main(String[] args) {
16         Kids kids=new Kids();
17         kids.add();
18         kids.fatherMethod();
19         System.out.println(kids.getAge());//用方法将父类的属性封装,用方法调用
20 
21     }
22 }

 

posted @ 2021-09-11 15:36  tiiiiii  阅读(37)  评论(0)    收藏  举报