super 关键字

调用父类构造器:

class Farther {
    Farther() {
        System.out.println("Farther");
    }
}

class Son extends Farther {
    Son() {
        // Constructor call must be the first statement in a constructor
        super();
        System.out.println("Son");
    }
}

public class Foo {
    public static void main(String[] args) {
        Son son = new Son();
    }
}

// Output:
// Farther
// Son

调用父类方法:

class Farther {
    Farther() {
        System.out.println("Farther");
    }

    void habit() {
        System.out.println("Farther's habit");
    }
}

class Son extends Farther {
    Son() {
        super();
        System.out.println("Son");
    }

    @Override
    void habit() {
        // Call farther's habit first
        super.habit();
        System.out.println("Son's habit");
    }
}

public class Foo {
    public static void main(String[] args) {
        Son son = new Son();
        son.habit();
    }
}

// Output:
// Farther
// Son
// Farther's habit
// Son's habit

Java 8, 多继承带默认方法的接口并覆盖默认方法时, 调用被继承接口中的其中一个:

interface Farther {
    default void habit() {
        System.out.println("Farther's habit");
    }
}

interface Mother {
    default void habit() {
        System.out.println("Mother's habit");
    }
}

// Notice this is interface implemention
class Son implements Farther, Mother {
    Son() {
        System.out.println("Son");
    }

    @Override
    public void habit() {
        // Notice 'Mother' before 'super'
        Mother.super.habit();
        System.out.println("Son's habit");
    }
}

// Output:
// Son
// Mother's habit
// Son's habit
Comments
Write a Comment