Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何访问子类的变量? public class Girl扩展了学生{…}//的名字、姓氏、id 公立班学生{…} 公立学校{ 学生[]arr=新女孩(名、姓、id) 对于(int i=0;i_Java_Arrays_Inheritance - Fatal编程技术网

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