gpt4 book ai didi

Java 继承和构造函数参数

转载 作者:行者123 更新时间:2023-11-29 09:43:54 25 4
gpt4 key购买 nike

我是 Java 业余爱好者,请帮助我。

我有一个类:Account

public class Account {
protected String fullName;
protected String accontNumber;
protected String password;
protected int balance;

public Account(String name, String acc_num, String pass, int b){
fullName = name;
accontNumber = acc_num;
password = pass;
balance = b;
}
}

我将创建一个继承自 Account 的新类 Account2

public class Account2 extends Account{
public Account2(String l){
String[] temp = l.split(",");
super.fullName = temp[0];
super.accontNumber = temp[1];
super.password = temp[2];
super.balance = Integer.parseInt(temp[3]);
}

}

但我收到一条错误消息:实际和形式参数列表的长度不同

我该如何解决这个问题?

最佳答案

当基类有一个非默认构造函数(一个或多个参数)时,派生类必须在其构造函数中用super(paramters)调用基类构造函数。还要注意constructor,第一行必须有super语句,所以必须声明一个相同参数的construct,或者在一行内正确传入参数,虽然不推荐这样做:

public Account2(String l) {
super(l.split(",")[0],l.split(",")[1],l.split(",")[2],Integer.parseInt(l.split(",")[3]));
}

关于Java 继承和构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20739868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com