super的常见用法

近期在补些Java的基础,遂作些许记录。

在 Java 中,super 是一个关键字,用于引用当前对象的父类(超类)成员。它的主要用途包括调用父类的构造方法、访问父类的方法和属性、以及解决方法覆盖问题。下面就这些用法进行展开,体会super关键字在Java中的应用:

1. 调用父类的构造方法

在子类的构造方法中,可以使用 super() 来调用父类的构造方法。这在父类构造方法需要初始化某些数据时特别有用。新手需要特别注意的是,super() 必须是构造方法中的第一行代码。

public class Main {
    public static void main(String[] args) {
        new Child();
    }
}

class Parent {
    Parent() {
        System.out.println("Parent constructor");
    }
}

class Child extends Parent {
    Child() {
        super(); // 调用父类的构造方法
        System.out.println("Child constructor");
    }
}

结果输出为:

Parent constructor
Child constructor

2. 访问父类的成员变量

如果子类中定义了与父类相同名字的成员变量,super 可以用来访问父类中的成员变量。

public class Main {
    public static void main(String[] args) {
        Child c = new Child();
        c.printName();
    }
}

class Parent {
    String name = "Parent";

    void printName() {
        System.out.println("Parent name: " + name);
    }
}

class Child extends Parent {
    String name = "Child";

    void printName() {
        super.printName(); // 调用父类的方法
        System.out.println("Child name: " + name);
    }
}

其中,在 Child 类的 printName 方法中,super.printName() 用于调用父类 Parent 的 printName 方法。

结果输出为:

Parent name: Parent
Child name: Child

3. 访问父类的方法

如果子类重写了父类的方法,可以使用 super 来调用被重写的方法。例如:

public class Main {
    public static void main(String[] args) {
        Child c = new Child();
        c.display();
    }
}

class Parent {
    void display() {
        System.out.println("Parent display");
    }
}

class Child extends Parent {
    void display() {
        super.display(); // 调用父类的方法
        System.out.println("Child display");
    }
}

结果输出为:

Parent display
Child display

4. 解决构造方法的冲突

在构造方法中,super() 调用父类的构造方法,确保父类部分的初始化在子类的初始化之前完成。这对于多层次继承关系特别重要。

public class Main {
    public static void main(String[] args) {
        new Child();
    }
}

class Grandparent {
    Grandparent() {
        System.out.println("Grandparent constructor");
    }
}

class Parent extends Grandparent {
    Parent() {
        super(); // 调用 Grandparent 的构造方法
        System.out.println("Parent constructor");
    }
}

class Child extends Parent {
    Child() {
        super(); // 调用 Parent 的构造方法
        System.out.println("Child constructor");
    }
}

结果输出为:

Grandparent constructor
Parent constructor
Child constructor

总结

super() :用于调用父类的构造方法,必须是构造方法中的第一行代码。

super.成员变量 :用于访问父类中的成员变量,特别是在子类中覆盖了父类的成员变量时。

super.方法名():用于调用父类中被子类重写的方法。

猜你喜欢

转载自blog.csdn.net/lingzhou0909/article/details/140663807