Skip to content

Java OOP; creating array of objects

I’d like to create an array of objects where 3 objects are from one class, and a 4th is from second class.

In the first class I did the following:

public class Pupil {
        public int n= 0;

        Pupil(int n) {
            this.n = n;} 

in the second class I did the following:

public class Tutor {
        public int m= 0;

        Tutor(int m) {
            this.m = m;} 

In the main class, I created several pupil objects and one tutor object, like this:

public class Main {
    public static void main (String[] args) {
        //Pupil(n) while for tutor objects it'd be Tutor(m) 
Pupil pupil1 = new Pupil(9);
Pupil pupil2 = new Pupil(8);
Pupil pupil3 = new Pupil(6); 
Tutor tutor1 = new Tutor(2);

Using objects for printing in main works fine.

But I’d like to create a fourth class where I group them into arrays of objects, but it won’t see the objects that I created to create groups out of them. I’m also not sure about the format for creating an array of objects.

public class Groups {

    public static void main(String [] args){

    Pupil [] g1 = {tutor1, pupil1, pupil2, pupil3};
    //cannot resolve any symbols 

EDIT: according to my tutor the groups class should be static to solve this, but I’m not sure how to actually code this?

Edit2: an answer pointed that the array should be Object as the above code would only be able to create an array of pupils, not pupils and tutors objects.

Object [] g1 = {tutor1, pupil1, pupil2, pupil3};

but that still doesn’t solve the main issue where no objects are seen from the groups class (//cannot resolve any symbols)


Arrays can only contain the same type of object. With that being said, here is a way:

Object[] g1 = {tutor1, pupil1, pupil2, pupil3};