gpt4 book ai didi

java - 如何通过继承来访问string的值?

转载 作者:行者123 更新时间:2023-11-30 01:42:13 25 4
gpt4 key购买 nike

import java.util.*;

class Pilot
{
protected String PILOT = "BSIT-1A";
public static void Subject()
{
String[] subs = {"Comprog11","WebDev","Digilog12","ComProg12"};
}
public static void Teacher()
{
String[] teach = {"Ms.a","Ms.b","Ms.c","Ms.d"};
}
}
class Pilot1 extends Pilot
{
protected String PILOT1 = "BSIT-1B";
public static void main(String[]args)
{
Pilot1 obj = new Pilot1();

System.out.println(obj.PILOT);
System.out.println(obj.PILOT1);
obj.Subject();
obj.Teacher();
}

如果我在其中放入一个字符串,如何显示 Subject() 和 Teacher() 的值?它没有任何编译器问题,但当我运行时,它只显示

BSIT-1A

BSIT-1B

我的预期输出是

BSIT-1A
BSIT-1B
Comprog11
Webdev
Digilog12
Comprog12
Ms.a
Ms.b
Ms.c
Ms.d

最佳答案

您可以返回数组

 public String[] subject() {
return {"Comprog11","WebDev","Digilog12","ComProg12"};
}

然后删除继承。 main 方法不需要它。将 Pilot 常量公开或将这些字符串传递到类构造函数中,并使用 getter 方法添加私有(private)字段,例如

    Pilot a = new Pilot("BSIT-1A");
Pilot b = new Pilot("BSIT-1B");
System.out.println(a.getCode());
System.out.println(b.getCode());
Arrays.stream(a.subject()).forEach(System.out::println);

关于java - 如何通过继承来访问string的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59553962/

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