Java 调用 super 必须是构造函数中的第一条语句,但它是

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16407455/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:44:16  来源:igfitidea点击:

Call to super must be first statement in the constructor, but it is

javaconstructorsuper

提问by Phil Meyer

I keep getting an error saying that "call to super must be the first statement in the constructor".

我不断收到一条错误消息,说“调用 super 必须是构造函数中的第一条语句”。

The problem is that it isthe first statement in my constructor.

问题是它我的构造函数中的第一条语句。

public void CheckingAccountCustomer(int a){
    super(n, p, b);
    accountNo = a;
}

And here is my superclass for this as well.

这也是我的超类。

public void customer(String n, int p, double b){
    name = n;
    pin = p;
    balance = b;
}

What am I doing wrong here?

我在这里做错了什么?

采纳答案by rgettman

This code

这段代码

public void customer(String n, int p, double b){

is not a constructor. Constructors don't have return types, e.g. void. Assuming your class name is customer:

不是构造函数。构造函数没有返回类型,例如void. 假设您的班级名称是customer

public customer(String n, int p, double b){

This applies to CheckingAccountCustomertoo.

这也适用CheckingAccountCustomer

回答by Hovercraft Full Of Eels

public void CheckingAccountCustomer(int a){

That's not a constructor since it states it has a voidreturn type. It's just a method of the same name as the class. Get rid of the return type.

那不是构造函数,因为它声明它具有void返回类型。它只是一个与类同名的方法。摆脱返回类型。

public CheckingAccountCustomer(int a){

回答by Eng.Fouad

public void CheckingAccountCustomer(int a)

This is a method not a constructor, since it has a return type.

这是一个方法而不是构造函数,因为它有一个返回类型。

回答by Maroun

The constructoris used to create an instance of that Class, so it make no sense if it will let the user to change the return type (it can be dangerous too). That's why constructors has noreturn type.

构造函数用于创建该类的实例,所以它没有任何意义,如果它会让用户更改返回类型(也可以是危险的也是如此)。这就是构造函数没有返回类型的原因。

As others have already answered, remove the return type and it'll become a constructor.

正如其他人已经回答的那样,删除返回类型,它将成为一个构造函数。

回答by javadev

Constructors never return something (either void or Object type).

构造函数从不返回任何东西(void 或 Object 类型)。

public void CheckingAccountCustomer(int a){
    super(n, p, b);
    accountNo = a;
}

thus is not a constructor.

因此不是构造函数。