Java - super关键字的使用

(摘自头歌)
任务描述

掌握super关键字的使用。

相关知识

1.super关键字;2.super关键字的使用;3.superthis关键字的比较。

super关键字

super主要的功能是完成子类调用父类中的内容,也就是调用父类中的属性或方法。

super关键字的使用

super关键字的用法如下:

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

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

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

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
    }
}

输出结果: black white

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

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

public class TestSuper2 {
    public static void main(String args[]) {
        Dog d = new Dog();
        d.work();
    }
}
class Animal {
    void eat() {
        System.out.println("eating...");
    }
}
class Dog extends Animal {
    void eat() {
        System.out.println("eating bread...");
}
    void bark() {
        System.out.println("barking...");
}
    void work() {
        super.eat();
        bark();
    }
}

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

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

public class TestSuper3 {
    public static void main(String args[]) {
        Dog d = new Dog();
    }
}
class Animal {
    Animal() {
        System.out.println("animal is created");
    }
}
class Dog extends Animal {
    Dog() {
        super();
        System.out.println("dog is created");
    }
}

输出结果: animal is created dog is created

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

superthis关键字的比较

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

范例:

public class TestAnimalDogDemo {
    public static void main(String[] args) {
        Animal a = new Animal();
        a.eat();
        Dog d = new Dog();
        d.eatTest();
    }
}
class Animal {
    void eat() {
        System.out.println("animal : eat");
    }
}
class Dog extends Animal {
    void eat() {
        System.out.println("dog : eat");
    }
    void eatTest() {
        this.eat(); // this 调用自己的方法
        super.eat(); // super 调用父类方法
    }
}

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

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

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值