gpt4 book ai didi

java - 无法理解Java中super的功能

转载 作者:行者123 更新时间:2023-12-01 13:51:54 26 4
gpt4 key购买 nike

首先,我将向您展示我的代码:

public class Person {
String _name;
int _age;
public Person(String name, int age){
_name = name;
_age = age;
}
public String toString(){
return "Age:" + _age + ". Name: " + _name;
}
}

public class Principal extends Person{
String _gender;
int _rank;
public Principal(String name, int age, String gender, int rank){
super(name, age);
_gender = gender;
_rank = rank;
}
public String toString(){
return "Age:" + _age + " .Name: " + _name + " .Gender: " + _gender + " .Rank: " + _rank;
}

}

主要:

public class Main {
public static void main(String[] args){
Person me = new Person("Bob", 23);
System.out.println(me);
Principal hj = new Principal("Dan", 39, "Male", 1);
}
}

我不明白为什么我必须在Principal hj = new Principal("Dan", 39, "Male", 1);中添加前2个参数。 。 。我以为super(name, age);应该从对象 me 继承前两个参数我只需要应用最后 2 个参数。

我误解了什么?

最佳答案

I thought that super(name, age); was supposed to inherit the first two parameters from the object me and I would only need to apply the last 2 parameters.

这意味着什么?
参数值必须来自某个地方

<小时/>

super(...) 只需调用基类构造函数,以及您想要传递给它的任何参数。

关于java - 无法理解Java中super的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19898405/

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