super关键字的使用

2021/8/5 23:09:24

本文主要是介绍super关键字的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

由上节内容可知,若子类中对某个方法进行了重写,调用时起作用的是子类中的方法。想要调用父类的方法必须在方法前加super.,如:
在InheritDog类中:

public void sleep(){
        super.eat();
        System.out.println(this.getName()+"现在"+this.getMonth()+"个月大,它在睡觉");
    }
package java_test;

import java_animal.InheritCat;
import java_animal.InheritDog;

public class AnimalTest {
    public static void main(String[] args) {
        InheritDog two = new InheritDog();
        two.setName("妞妞");
        two.setMonth(2);
        two.sleep(); 
    }
}

输出:

妞妞在吃东西
妞妞现在2个月大,它在睡觉

也可通过 super.成员 的方法对父类的属性进行调用。但是父类的构造不允许被继承、不允许被重写。



这篇关于super关键字的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程