【发布时间】:2016-11-21 09:00:27
【问题描述】:
我想使用对象数组“arr”访问变量“s”?请参考代码sn-p。
public class Array_Chp3 {
public static void main(String[] args) {
Array_Chp3[] arr = new Array_Chp3[3];
arr[0] = new str(); // when used this line instead of the below line , getting the error "s cannot be resolved or is not a field"
//arr[0] = new Array_Chp3(); // when used this line instead of the above line, getting the error s cannot be resolved or is not a field
str obj = new str();
System.out.println(arr[0]);
System.out.println(arr.length);
System.out.println(arr[0].s); // How to access the variable 's'?
}
}
class str extends Array_Chp3{
public String s = "string123 @ str";
}
错误信息: 线程“main”java.lang.Error 中的异常:未解决的编译问题: s 无法解析或不是字段 在 Array_Chp3.main(Array_Chp3.java:17)
【问题讨论】:
-
你需要一个在str类中的getter,它会返回s。然后你可以把它叫做
arr[].getS(); -
您没有显示您的
str类的代码(顺便说一句,应该以大写首字母命名,Str)。它是否有一个可以从那里访问的字段s? -
@SantiBailors 是的,他确实显示了
str的代码。阅读问题。 -
@JBNizet 对,我错过了,我很抱歉。
标签: java inheritance arrayobject