I have made a 2-d array which will store references to objects of the children classes of parent class Student.
Student[][] a = new Student [5][4];
Now I want to initialize this array with null? How do I do it? Any trick to doing it at once? Also, I Wanted to know if it is possible to store references of children class in an array of Base class in Java?
I want to initialize all the values with null. Also, let's say some values are filled and then I want to overwrite the values with null. How do I do that?
By default JAVA initialises the reference objects with null.
There are three ways, choose the most priority for you.
Student[][] a = null; // reference to a equals null
Student[][] a = new Student[5][]; // {null, null, null, null, null}
Student[][] a = new Student[5][5]; // {{null, null, null, null, null}, {...}, ...}
For your purpose (from the comment), you could use Arrays.fill(Object[] a, Object val). For example,
for(Student[] array : a) Arrays.fill(array, null);
or
for(int i = 0; i < a.length; ++i)
for(int j = 0; j < a[i].length; ++j)
a[i][j] = null;
Also, I Wanted to know if it is possible to store references of children class in an array of Base class in Java?
Yes, that's possible. The process named upcasting (SubStudent is upcasted to Student).
a[0][0] = new SubStudent();
a[0][1] = new Student();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With