java中super常见用法

1.显式调用父类的构造函数,因为父类没有无参构造函数,所有子类在继承的时候必须显式调用父类的构造函数来初始化父类。 

class Parent {
    int num;

    Parent(int n) {
        num = n;
        System.out.println("Parent constructor called.");
    }
}

class Child extends Parent {
    String name;

    Child(int n, String s) {
        super(n); // 显式调用父类的有参构造函数
        name = s;
        System.out.println("Child constructor called.");
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child(5, "Tom");
    }
}

2.访问父类的成员变量、方法

   class Parent {
       int num = 10;
   }

   class Child extends Parent {
       int num = 20;

       void printNum() {
           System.out.println("Child's num: " + num);
           System.out.println("Parent's num: " + super.num);
       }
   }

   public class Main {
       public static void main(String[] args) {
           Child child = new Child();
           child.printNum();
       }
   }

3.在重写方法中调用父类方法并实现增强

   class Parent {
       void doSomething() {
           System.out.println("Parent is doing something.");
       }
   }

   class Child extends Parent {
       @Override
       void doSomething() {
           super.doSomething();
           System.out.println("Child is doing something more.");
       }
   }

   public class Main {
       public static void main(String[] args) {
           Child child = new Child();
           child.doSomething();
       }
   }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值