Objects are instances of a class. To avoid declaring several objects of same type, Java allows us to create arrays of objects. These arrays are similar to ordinary arrays. Every array element is an object with same properties. To access objects of an array of objects we use array name with a unique index. To create array of objects, we first create the array and allocate memory for each object separately.
Example:
class Student
{
private String name[20];
private int rno;
void setData(String n, int r)
{
name=n;
rno=r;
}
void showData()
{
System.out.println(name+”\t”+rno);
}
}
class Test
{
public static void main(String as[])
{
Student s[] = new Student[2];
s[0] = new Student();
s[1] = new Student();
s[0].setData(“Ravi”,33);
s[1].setData(“Kiran”,44);
s[0].showData();
s[1].showData();
}
}
Explanation:
In the above example, we have taken “student” array i.e. s[]. Every object i.e. s[0], s[1] will have both the properties “name” and “rno”. To access the member functions of the class with the array objects, we use s[0].setData(), s[1].setData() and so on.
0 comments:
Post a Comment