java 调用 super()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2632882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling super()
提问by SIr Codealot
When do you call super() in Java? I see it in some constructors of the derived class, but isn't the constructors for each of the parent class called automatically? Why would you need to use super?
你什么时候在 Java 中调用 super() ?我在派生类的一些构造函数中看到了它,但是每个父类的构造函数不是自动调用的吗?为什么需要使用超级?
回答by TofuBeer
If you provide a class like this:
如果您提供这样的类:
public class Foo
{
}
or this:
或这个:
public class Foo()
{
public Foo()
{
}
}
the compiler will generate code for this:
编译器将为此生成代码:
public class Foo()
{
public Foo()
{
super();
}
}
So, strictly speaking, the call to "super()" is always there.
因此,严格来说,对“super()”的调用始终存在。
In practice you should only call "super(...)" where there are parameters you want to pass to the parent constructor.
在实践中,您应该只在有要传递给父构造函数的参数的地方调用“super(...)”。
It isn't wrong to call "super()" (with no parameters) but people will laugh at you :-)
调用“super()”(没有参数)并没有错,但人们会嘲笑你:-)
回答by Skrud
You would needto use super()in a case like this:
您需要super()在这样的情况下使用:
public class Base {
public Base(int foo) {
}
}
public class Subclass extends Base {
public Subclass() {
super(15);
}
}
This is a very contrived example, but the only time that you needto call super()is if you're inheriting from a class that doesn't provided a default, parameterless constructor. In this cases you need to explicitly call super()from the constructor of your subclass, passing in whatever parameters you need to satisfy the base class's constructor. Also, the call to super()must be the firstline of your inherited class's constructor.
这是一个非常人为的示例,但您唯一需要调用的情况super()是,如果您从未提供默认无参数构造函数的类继承。在这种情况下,您需要super()从子类的构造函数中显式调用,传入满足基类构造函数所需的任何参数。此外,调用super()必须是继承类的构造函数的第一行。
回答by Matthew Flynn
As has been said, if your constructor does not explicitly call super() with or without some argument, java will automatically call the default constructor of the superclass.
如前所述,如果您的构造函数没有显式调用 super() 带或不带参数,java 将自动调用超类的默认构造函数。
However, explicitly calling super() is just that--explicit. If you know the superclass's constructor does something significant, it's a useful reminder to whomever is maintaining your code that super() is being called first (and may have side effects). This might even be a useful spot to put a breakpoint while debugging.
然而,显式调用 super() 就是这样——显式。如果您知道超类的构造函数做了一些重要的事情,那么这对于维护您的代码的人来说是一个有用的提醒,即首先调用 super() (并且可能有副作用)。这甚至可能是在调试时放置断点的有用位置。
回答by stacker
There is no need to call super().
不需要调用 super()。
From Accessing Superclass Members:
从访问超类成员:
With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.
使用 super() 调用超类无参数构造函数。使用 super(parameter list) 调用具有匹配参数列表的超类构造函数。
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.
注意:如果构造函数没有显式调用超类构造函数,Java 编译器会自动插入对超类的无参数构造函数的调用。如果超类没有无参数构造函数,您将收到编译时错误。Object 确实有这样的构造函数,所以如果 Object 是唯一的超类,就没有问题。
回答by Edwin Buck
If you fail to call super in a constructor, then the compiler will add a no-argument super call as the parent constructor for the first line of the constructor body.
如果在构造函数中调用 super 失败,那么编译器将添加一个无参数的 super 调用作为构造函数主体第一行的父构造函数。
So as in the previously posted code
就像之前发布的代码一样
public class Foo
{
}
or
或者
public class Foo
{
public Foo()
{
}
}
the compiler will generate code that aligns with the rules of Java. All objects are subclasses of java.lang.Object, so the compiler will compile it as if it was written
编译器将生成符合 Java 规则的代码。所有对象都是 java.lang.Object 的子类,所以编译器会像写的一样编译它
// All classes extend Object. This is Java, after all.
public class Foo extends java.lang.Object
{
public Foo()
{
// When constructing Foo, we must call the Object() constructor or risk
// some parts of Foo being undefined, like getClass() or toString().
super()
}
}
But if the super class doesn't have a constructor that matches the parameters, then you must call the appropriate non-matching super class constructor.
但是如果超类没有与参数匹配的构造函数,那么您必须调用适当的非匹配超类构造函数。
public class LightBlue extends java.awt.Color
{
public LightBlue()
{
// There is no Color() constructor, we must specify the suitable super class
// constructor. We chose Color(int red, int green, int blue).
super(172, 216, 230);
}
}
Other times, perhaps there is a constructor that matches the signature of the sub class's constructor, but for whatever reason, you do not wish to pass the parameters directly to the super class constructor.
其他时候,也许有一个构造函数与子类的构造函数的签名相匹配,但无论出于何种原因,您都不希望将参数直接传递给超类构造函数。
public class HSVColor extends Color
{
public HSVColor(int hue, int saturation, int value)
{
super(...code converting HSV to Red...,
...code converting HSV to Green...,
...code converting HSV to Blue);
}
}
If you neglect to explicitly specify the super class constructor, then the compiler adds in the default no-arg super class constructor. However, if that constructor doesn't exist, then the compiler will not compile the class, because it is unclear which of the exposed constructors is the correct one to call.
如果您忽略显式指定超类构造函数,则编译器会添加默认的无参数超类构造函数。但是,如果该构造函数不存在,则编译器将不会编译该类,因为不清楚要调用哪个公开的构造函数是正确的。
It is a style consideration, but you may decide to always include the super() call. If you chose to do so, it will be because you want the remind the reader that the base class objects must be built as part of the sub class object, and you want to make the particular super class constructor explicit. Traditionally, an always included super() call is quite odd, since traditionally code is only typed out if it differs from "default" behaviour.
这是一种风格考虑,但您可能决定始终包含 super() 调用。如果你选择这样做,那是因为你想提醒读者基类对象必须作为子类对象的一部分构建,并且你想让特定的超类构造函数显式。传统上,始终包含的 super() 调用很奇怪,因为传统上只有在与“默认”行为不同时才会输入代码。
回答by user2911290
I wanted to provide some information that hasn't been mentioned so far. If you use a call to this(...)in a constructor, then you can't have a call to super(...);This also includes Java's automatic insertion of the parameterless call to super();
我想提供一些目前尚未提及的信息。如果this(...)在构造函数中使用了调用,那么就不能调用 tosuper(...);这也包括 Java 自动插入的无参数调用super();
The following example illustrates this point, including explanatory comments:
以下示例说明了这一点,包括解释性注释:
public class B extends A {
private int x;
public B() {
// Java doesn't call super(); here, because
// of the call to this(...); below.
// You can't call super(...) here either,
// for the same reason.
this(42); // Calls public B(int x) below.
}
public B(int x) {
// Java does call super(); here.
// You can call super(...) here, if you want/need to.
// The net result of calling new B() above is that
// super(...) for class A only gets called once.
this.x = x;
}
}
回答by Mohamad Alhamoud
When you have a class that extends another class and the father class have no default constructor then you have to use super() in the Son's constructor to call the constructor in the Father Class with the proper arguments like this :
当您有一个扩展另一个类的类并且父类没有默认构造函数时,您必须在 Son 的构造函数中使用 super() 以使用正确的参数调用父类中的构造函数,如下所示:
class A
{
int a;
A(int value)
{
this.a=value;
System.out.println("A Constructor " + a );
}
}
class B extends A
{
int b;
B()
{
super(5);
this.b=10;
System.out.println("B Constructor " + b);
}
}
you have to know that yo can't use "super" with "this" if you want to call another constructor in the calss using "this".
您必须知道,如果您想使用“this”调用 calss 中的另一个构造函数,则不能将“super”与“this”一起使用。
回答by sparkyspider
Although super()does nothing functionally for the compiler (the superclass default constructor is called automatically), it certainly does a lot for me. It says to me: "Do not remove the empty constructor. It's there for a reason".
尽管super()在功能上对编译器没有任何作用(自动调用超类默认构造函数),但它确实对我有很大帮助。它对我说:“不要删除空的构造函数。它的存在是有原因的”。
A perfect example is where you create Spring managed beans or JPA Entities and you've created a parameterized constructor.
一个完美的例子是您创建 Spring 托管 bean 或 JPA 实体并创建了一个参数化构造函数。
@Entity
public class Portfolio {
...
public Portfolio() {
super(); // This says to me: DON'T DELETE!
}
/**
* Because there is now a parameterised constructor (me),
* the default constructor no longer exists. This means
* that for this example, you need an empty constructor in place (above)
**/
public Portfolio(String name) {
this.name = name;
}
}
回答by Android
Super is called when we want to inherit some of the parameters from the parent class. It is not compulsory as the compiler always call the default constructor. If you want to inherit a constructor having some parameters then you need to call the super. So you can use it.
当我们想从父类继承一些参数时调用super。这不是强制性的,因为编译器总是调用默认构造函数。如果要继承具有某些参数的构造函数,则需要调用 super. 所以你可以使用它。
回答by Tedil
Because the super class' constructor is not called automatically. There might, for example, be several constructors, some of which take additional parameters. So you do not always have got an "empty" super() statement, but something like this:
因为不会自动调用超类的构造函数。例如,可能有多个构造函数,其中一些带有附加参数。所以你并不总是有一个“空”的 super() 语句,而是这样的:
public class DerivedClass extends SomeOtherClass
{
private String anotherParameter;
public DerivedClass(int parameterA, String parameterB, String anotherParameter)
{
super(parameterA, parameterB);
this.anotherParameter = anotherParameter;
}
}
Edit:I obviously forgot to say (or my choice of words simply wasn't good, but I'm no native speaker, sorry for that) that if the super class does not take any parameters, the call to super() will be done for you by java/the compiler. (Now that I re-read my answer, I can see that it really sounds like you would always have to call super().)
编辑:我显然忘了说(或者我选择的词根本不好,但我不是母语人士,抱歉)如果超类不接受任何参数,则对 super() 的调用将是由 java/编译器为您完成。(现在我重新阅读了我的答案,我可以看到这听起来真的就像您总是必须调用 super()。)

