Xaad Xadiq Xaad Xadiq - 1 month ago 12
Java Question

How to read and write Object Arrays in JAVA ? I am facing Problems

I am having 10 Classes and I Have linked them like that
class Person is linked in class Array ,I have taken an array of objects in Array Class like this

Person [] p = new Person[99];

public void generate(){

for(int i=0;i<=p.length-1;i++)
{
p[i]=new Person();//this will allocate space for Persons
}
}


Now how can i write the Data of each index stored by some Other class ?
and How can i read after terminating it.?
Thanks indeed

Answer

To access the element of an array, you can simply use the index of an element:

Person perfonFromIndex = p[index];

If you want to store objects, of different types in same array, you can declare this array of type from which all of your classes are derived, for example Object class: Object[] p = new Object[99];

public void generate(){
  for(int i=0;i<p.length;i++)
  {
     p[i]=new Person();//this will allocate space for Persons
  }
}

But in that case, you have to cast every time you want to get an element of sepcified class:

SpecifiedClass perfonFromIndex = (SpecifiedClass)p[index];

It's quite bad sollution. Better thing is to achieve it by using polymorphysm:

class Base{
    void method(){
        System.out.println("from Base");
    }
}
class Derived1 extends Base{
    @Override
    void method(){
        System.out.println("from Derived1");
    }
}
class Derived2 extends Base{
    @Override
    void method(){
        System.out.println("from Derived2");
    }
}

Since now, you won't have to cast every time, you want to call the method() of specified time, java compiler will know which method should be invoked:

Base[] arr = new Base[3];
arr[0] = new Base();
arr[1] = new Derived1();
arr[2] = new Derived2();
for(Base b : arr){
    b.method();
}

And the output is:

from Base
from Derived1
from Derived2

For more about polymorphism you can read here.