super keyword

  • super is a reference to the immediate parent class object. You can use super to access methods and properties in the parent class that are overridden by the child class.
  • Common method:
    1. There is no order restriction, you can call it at will.

  • In the constructor:
    1. In the constructor of any class, if the first line of code of the constructor does not explicitly call
    super(….); then Java will call super(); as the initialization function of the parent class by default. So it doesn't matter if you add super() here or not.

package theChildOfGod.bjxy.oop.inherit;

public class Animal{
    String eye;

    public Animal() { //即使不写,构造方法这也是默认的。
        super();
        System.out.println("建一只动物");
    }
    public void run() {
        System.out.println("跑跑!");
    }
    public void eat() {
        System.out.println("吃吃!");
    }
    public void sleep() {
        System.out.println("zzzzzz");
    }
}
class Mammal extends Animal{
    public Mammal() {
        super();
        System.out.println("建一只哺乳动物");
    }
    public void taisheng() {
        System.out.println("我是胎生");
    }
}
class Bird extends Animal{ 

    public Bird() {
        super();
        System.out.println("建一只鸟");
    }
    public void run(){
        System.out.println("我是一只小小鸟!飞呀飞不高!");
    }
    public void eggSheng() {
        System.out.println("卵生");
    }
}

package theChildOfGod.bjxy.oop.inherit;

public class Test {

    public static void main(String[] args) {
        Bird b = new Bird();
        b.run();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324516319&siteId=291194637