super关键字的使用


java中的super关键字是一个引用变量,用于引用直接父类对象。
super关键字用法如下:

  • 可以用来引用直接父类的实例变量。
  • 可以用来调用直接父类方法。
  • 可以用于调用直接父类构造函数。

直接引用父类的实例变量

可以使用super关键字来访问父类的数据成员或字段。 如果父类和子类具有相同的字段,则使用super来指定为父类数据成员或字段。
示例:

class Animal {
    String color = "white";
}

class Dog extends Animal {
    String color = "black";

    void printColor() {
        System.out.println(color);                                                 // prints color of Dog class
        System.out.println(super.color);                                      // prints color of Animal class
    }
}

class TestSuper1 {
    public static void main(String args[]) {
        Dog d = new Dog();
        d.printColor();
    }
}

输出结果

black
white

通过 super 来调用父类方法

super关键字也可以用于调用父类方法。 如果子类包含与父类相同的方法,则应使用super关键字指定父类的方法。 换句话说,如果方法被覆盖就可以使用 super 关键字来指定父类方法。
示例

class Animal {
    void eat() {
        System.out.println("eating...");
    }
}

class Dog extends Animal {
    @override
    void eat() {
        System.out.println("eating bread...");
    }

    void bark() {
        System.out.println("barking...");
    }

    void work() {
        super.eat();
        bark();
    }
}

class TestSuper2 {
    public static void main(String args[]) {
        Dog d = new Dog();
        d.work();
    }
}

结果

eating...
barking...

使用super来调用父类的构造函数

示例

class Animal {
    Animal() {
        System.out.println("animal is created");
    }
}

class Dog extends Animal {
    Dog() {
        super();
        System.out.println("dog is created");
    }
}

class TestSuper3 {
    public static void main(String args[]) {
        Dog d = new Dog();
    }
}

输出结果

animal is created
dog is created

实例

class Person {
    int id;
    String name;

    Person(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

class Emp extends Person {
    float salary;

    Emp(int id, String name, float salary) {
        super(id, name);// reusing parent constructor
        this.salary = salary;
    }

    void display() {
        System.out.println(id + " " + name + " " + salary);
    }
}

class TestSuper5 {
    public static void main(String[] args) {
        Emp e1 = new Emp(1, "ankit", 45000f);
        e1.display();
    }
}

结果

1 ankit 45000.0
  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值