2024-12-14 08:00:05

Java中的super()

super()用于调用父构造函数吗? 请解释super()。


当前回答

我已经看到了所有的答案。但大家都忘了提一个非常重要的问题:

Super()应该在构造函数的第一行中调用或使用。

其他回答

调用无参数的超级构造函数只是浪费屏幕空间和程序员时间。编译器生成的代码完全相同,不管你写不写。

class Explicit() {
    Explicit() {
        super();
    }
}

class Implicit {
    Implicit() {
    }
}

super关键字可用于调用超类构造函数和引用超类的成员

当您使用正确的参数调用super()时,实际上调用了构造函数Box,它通过使用相应参数的值来初始化变量width、height和depth。你只剩下初始化它的增值权重。如果有必要,现在可以将类变量Box设为私有。放在Box类私有修饰符的字段中,并确保您可以毫无问题地访问它们。

在超类中可以有多个重载版本的构造函数,因此可以使用不同的参数调用方法super()。程序将执行与指定参数匹配的构造函数。

public class Box {

    int width;
    int height;
    int depth;

    Box(int w, int h, int d) {
        width = w;
        height = h;
        depth = d;
    }

    public static void main(String[] args){
        HeavyBox heavy = new HeavyBox(12, 32, 23, 13);
    }

}

class HeavyBox extends Box {

    int weight;

    HeavyBox(int w, int h, int d, int m) {

        //call the superclass constructor
        super(w, h, d);
        weight = m;
    }

}

我们可以用SUPER做什么?

访问超类成员

如果你的方法覆盖了它的一些超类的方法,你可以通过使用关键字super来调用被覆盖的方法,比如super. methodname ();

调用超类构造函数

如果构造函数没有显式调用超类构造函数,Java编译器会自动插入对超类的无参数构造函数的调用。如果超类没有无参数构造函数,则会得到编译时错误。

看看下面的代码:


class Creature {
    public Creature() {
        system.out.println("Creature non argument constructor.");
    }
}

class Animal extends Creature {
    public Animal (String name) {
        System.out.println("Animal one argument constructor");
    }
    public Animal (Stirng name,int age) {
        this(name);
        system.out.println("Animal two arguments constructor");
    }
}

class Wolf extends Animal {
    public Wolf() {
        super("tigerwang",33);
        system.out.println("Wolf non argument constructor");
    }
    public static void main(string[] args) {
        new Wolf();
    }
}

When creating an object,the JVM always first execute the constructor in the class of the top layer in the inheritance tree.And then all the way down the inheritance tree.The reason why this is possible to happen is that the Java compiler automatically inserts a call to the no-argument constructor of the superclass.If there's no non-argument constructor in the superclass and the subclass doesn't explicitly say which of the constructor is to be executed in the superclass,you'll get a compile-time error.

类的构造函数,在上面的代码中,如果我们想成功地创建Wolf对象 类必须执行。在这个过程中,Animal中的双参数构造函数 类被调用。同时,它显式地调用同一个参数中的单参数构造函数 类和单参数构造函数隐式调用生物中的非参数构造函数 类和非参数构造函数再次隐式调用Object中的空构造函数 类。

super()是用来调用父构造函数吗?

是的。

请解释一下超级()。

Super()是Super关键字的一种特殊用法,用于调用无参数的父构造函数。通常,super关键字可用于调用被重写的方法、访问隐藏字段或调用超类的构造函数。

下面是官方教程

Super是一个关键词。在子类方法定义中使用它来调用父类中定义的方法。父类的私有方法不能被调用。只有public和protected方法可以被super关键字调用。类构造函数也使用它来调用父类的构造函数。

点击这里查看进一步的解释。