2024-12-14 08:00:05

Java中的super()

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


当前回答

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

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

class Implicit {
    Implicit() {
    }
}

其他回答

是的,super()(小写)调用父类的构造函数。可以包含参数:super(foo, bar)

还有一个超级关键字,您可以在方法中使用它来调用超类的方法

“Java super”的快速谷歌会导致这样的结果

构造函数 在构造函数中,可以使用它而不带点来调用另一个构造函数。Super调用父类中的构造函数;调用该类中的构造函数:

public MyClass(int a) {
  this(a, 5);  // Here, I call another one of this class's constructors.
}

public MyClass(int a, int b) {
  super(a, b);  // Then, I call one of the superclass's constructors.
}

Super在父类需要初始化自身时很有用。这允许您只在一个构造函数中编写一次所有硬初始化代码,并从所有其他更容易编写的构造函数调用它,这很有用。

方法 在任何方法中,都可以使用它和一个点来调用另一个方法。Super.method()调用超类中的方法;this.method()调用该类中的一个方法:

public String toString() {
  int    hp   = this.hitpoints();  // Calls the hitpoints method in this class
                                   //   for this object.
  String name = super.name();      // Calls the name method in the superclass
                                   //   for this object.

  return "[" + name + ": " + hp + " HP]";
}

super在某些情况下是有用的:如果你的类和你的超类有相同的方法,Java会假设你想在你的类中使用这个方法;Super允许你请求父类的方法。这只在提高代码可读性时有用。

来源文章: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关键字调用。类构造函数也使用它来调用父类的构造函数。

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

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

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

class Implicit {
    Implicit() {
    }
}