Java 如何访问子类的变量? public class Girl扩展了学生{…}//的名字、姓氏、id 公立班学生{…} 公立学校{ 学生[]arr=新女孩(名、姓、id) 对于(int i=0;i
您可以检查Java 如何访问子类的变量? public class Girl扩展了学生{…}//的名字、姓氏、id 公立班学生{…} 公立学校{ 学生[]arr=新女孩(名、姓、id) 对于(int i=0;i,java,arrays,inheritance,Java,Arrays,Inheritance,您可以检查 public class Girl extends Student{...} //has firstname, lastname, id public class Student {...} public class School{ Student[] arr = new girl(firstname, lastname, id) for(int i = 0; i<arr.length; i++){ arr.getID(); //
public class Girl extends Student{...} //has firstname, lastname, id
public class Student {...}
public class School{
Student[] arr = new girl(firstname, lastname, id)
for(int i = 0; i<arr.length; i++){
arr.getID(); //does this work if I have a getter in Girl class?
}
}
不能直接调用getID()学生对象。必须将该学生对象强制转换为Girl对象,然后才能使用Girl类方法访问它。首先,需要新的serverl girls来填充Student[]arr
if (arr[i] instanceof Girl)
{
Girl girl = (Girl)arr[i];
...
然后使用getter投掷进入女孩的场地
Student[] arr = new Student[num];
arr[0] = new girl();
arr[1] = new girl();
etc..
希望能解决您的问题。为什么
Student
没有这些属性?名字、姓氏和id似乎是所有学生的共同属性。
arr[i].getter