0

I created an array of objects like this:

Handler handlers[] = new Handler[4];

Each handler object takes in a socket object as parameter. How do I pass through the socket for the handlers? I guess more generally how do I pass through arguments in an array of objects?

I've tried this:

handlers[1](someSocket);

and it (obviously?) didn't work.

2
  • 2
    You've created an array. You haven't created any Handler objects. Commented Jan 26, 2015 at 0:57
  • @SotiriosDelimanolis okay, wow I think I've figured it out. Would I do this for all of the members of the array: handlers[0] = new Handler(listener.accept()); Commented Jan 26, 2015 at 1:00

2 Answers 2

3

This

Handler handlers[] = new Handler[4];

Allocates room for 4 Handler instances, it doesn't allocate any actual Handler(s). You could do something like,

Handler[] handlers = new Handler[4];
for (int i = 0; i < handlers.length; i++) {
  handlers[i] = new Handler();
}

or even

Handler[] handlers = new Handler[] {
  new Handler(), new Handler(), new Handler(), new Handler()
};
Sign up to request clarification or add additional context in comments.

Comments

1

Iterate over each element in the array. Create a new handler, pass it a socket, and store it in the array like this:

Handler handlers[] = new Handler[4];
for(int index=0;index<4;index++){
    handlers[index]= new Handler(socket);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.