JAVA Super关键字


任务描述

本关任务:掌握super关键字的使用。

相关知识

为了完成本关任务,你需要掌握:1.super关键字;2.super关键字的使用;3.superthis关键字的比较。

super关键字

在上一节中曾经提到过super的使用,那super到底是什么呢?super关键字出现在子类中,我们new子类的实例对象的时候,子类对象里面会有一个父类对象。怎么去引用里面的父类对象呢?使用super来引用,所以可以得出结论:super主要的功能是完成子类调用父类中的内容,也就是调用父类中的属性或方法。

super关键字的使用

super关键字的用法如下:

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

1.super用于引用直接父类实例变量

 
  1. public class TestSuper1 {
  2. public static void main(String args[]) {
  3. Dog d = new Dog();
  4. d.printColor();
  5. }
  6. }
  7. class Animal {
  8. String color = "white";
  9. }
  10. class Dog extends Animal {
  11. String color = "black";
  12. void printColor() {
  13. System.out.println(color);// prints color of Dog class
  14. System.out.println(super.color);// prints color of Animal class
  15. }
  16. }

输出结果: black white

在上面的例子中,AnimalDog都有一个共同的属性:color。 如果我们打印color属性,它将默认打印当前类的颜色。要访问父属性,需要使用super关键字指定。

2.通过super来调用父类方法

 
  1. public class TestSuper2 {
  2. public static void main(String args[]) {
  3. Dog d = new Dog();
  4. d.work();
  5. }
  6. }
  7. class Animal {
  8. void eat() {
  9. System.out.println("eating...");
  10. }
  11. }
  12. class Dog extends Animal {
  13. void eat() {
  14. System.out.println("eating bread...");
  15. }
  16. void bark() {
  17. System.out.println("barking...");
  18. }
  19. void work() {
  20. super.eat();
  21. bark();
  22. }
  23. }

输出结果: eating... barking... 在上面的例子中,AnimalDog两个类都有eat()方法,如果要调用Dog类中的eat()方法,它将默认调用Dog类的eat()方法,因为当前类的优先级比父类的高。所以要调用父类方法,需要使用super关键字指定。

3.使用super来调用父类构造函数

 
  1. public class TestSuper3 {
  2. public static void main(String args[]) {
  3. Dog d = new Dog();
  4. }
  5. }
  6. class Animal {
  7. Animal() {
  8. System.out.println("animal is created");
  9. }
  10. }
  11. class Dog extends Animal {
  12. Dog() {
  13. super();
  14. System.out.println("dog is created");
  15. }
  16. }

输出结果: animal is created dog is created

注意:如果没有使用super()this(),则super()在每个类构造函数中由编译器自动添加。

superthis关键字的比较

super关键字:我们可以通过super关键字来实现对父类成员的访问,用来引用当前对象的父类。 this关键字:指向自己的引用。 范例:

 
  1. public class TestAnimalDogDemo {
  2. public static void main(String[] args) {
  3. Animal a = new Animal();
  4. a.eat();
  5. Dog d = new Dog();
  6. d.eatTest();
  7. }
  8. }
  9. class Animal {
  10. void eat() {
  11. System.out.println("animal : eat");
  12. }
  13. }
  14. class Dog extends Animal {
  15. void eat() {
  16. System.out.println("dog : eat");
  17. }
  18. void eatTest() {
  19. this.eat(); // this 调用自己的方法
  20. super.eat(); // super 调用父类方法
  21. }
  22. }

输出结果: animal : eat dog : eat animal : eat

上表对 this super 的差别进行了比较,从上表中不难发现,用 super this 调用构造方法时都需要放在首行,所以superthis 调用构造方法的操作是不能同时出现的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值