2024-12-14 08:00:05

Java中的super()

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


当前回答

这是正确的。Super用于调用父构造函数。假设你有这样一个代码块

class A{
    int n;
    public A(int x){
        n = x;
    }
}

class B extends A{
    int m;
    public B(int x, int y){
        super(x);
        m = y;
    }
}

然后你可以给成员变量n赋一个值。

其他回答

来源文章:Java:调用super()


是的。Super(…)将调用超类的构造函数。

说明:

独立的例子:

class Animal {
    public Animal(String arg) {
        System.out.println("Constructing an animal: " + arg);
    }
}

class Dog extends Animal {
    public Dog() {
        super("From Dog constructor");
        System.out.println("Constructing a dog.");
    }
}

public class Test {
    public static void main(String[] a) {
        new Dog();
    }
}

打印:

Constructing an animal: From Dog constructor
Constructing a dog.

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

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

我们可以用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用于调用父构造函数。假设你有这样一个代码块

class A{
    int n;
    public A(int x){
        n = x;
    }
}

class B extends A{
    int m;
    public B(int x, int y){
        super(x);
        m = y;
    }
}

然后你可以给成员变量n赋一个值。

The super keyword in Java is a reference variable that is used to refer to the immediate parent class object.

Java超级关键字的使用

Super可用于引用直接父类实例变量。 Super可用于调用直接父类方法。 Super()可用于调用直接父类构造函数。