gpt4 book ai didi

java - 如何返回一个子类独有的变量?

转载 作者:行者123 更新时间:2023-12-02 00:57:50 26 4
gpt4 key购买 nike

我有一个类Person,它有多个子类。所有子类都有相同的变量(nameaddressphone),但有一个额外的变量,rank 。我知道如何显示姓名地址电话,但我不知道如何显示排名

定义类:

public class Person {
public String name;
public String address;
public String phone;

public Person(String name, String address, String phone) {
this.name = name;
this.address = address;
this.phone = phone;
}

public String toString() {
return this.getClass().getName() + "\n" + name;
}
}

使用rank定义子类:

public class Pupil extends Person {
public String rank;
public Student(String name, String address, String phone, String rank) {
super(name, social, phone);
}

}

创建学生并显示姓名地址电话

public class Test {

public static void main(String[] args) {
Person person = new Person("John", "1 John Deer Rd", "1112223333");
Person pupil = new Pupil("Jane", "2 John Deer Rd", "1112223333", "junior");


System.out.println(pupil.name + "'s phone is " + pupil.phone + " and their address is " + pupil.address + "." + "\n");

}
}

如何显示排名

最佳答案

您必须将对象从 Person 转换回 Pupil:

((瞳孔)瞳孔).rank

如果您不能 100% 确定您的对象实际上是学生,您应该添加健全性检查:

if(pupil instanceof Pupil) {
System.out.println(…+((Pupil)pupil).rank+…);
}

关于java - 如何返回一个子类独有的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61102962/

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