• Post Reply Bookmark Topic Watch Topic
  • New Topic

creating objects  RSS feed

Mervin Chan
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One question about creating objects.

say i have a simple object.

Foo(int id)

i can create seperate objects by doing

Foo a = new Foo(1);
Foo b = new Foo(2);

but as each object can be referenced a seperate id number, by doing

for(int i=0;i<10;i++)
Foo A = new Foo(i);

1) Do i get 10 seperate Foo objects named A?

2)in addition, if the answer to part 1 of my question is Yes, then how to i
find out about say object 2 of Foo A ?

ie usually i can do A.doSomething(); B.doSomething();

but if i create my objects using the loop, how do i want object 2 to do a method? A2.doSomething() //???

I am thinking the solution is storing them in list/array, and referencing them using the list/arrary. Am i right?

but the question remains, is Foo A = new Foo(1); and Foo A = new Foo(2);
considered seperate objects?

thanks for the help!
Jeanne Boyarsky
author & internet detective
Posts: 37496
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch!

1) Yes, 10 separate objects are created. However, they are not accessible outside the loop because A is declared in the loop. Even if A was declared outside the loop, it can only point to one object at a time. So only the last one would be accessible.

2) Yes, you need to store them in a list/array.

So they are separate objects, but only one is accessible.
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, I'd like to clarify some terminology. "Foo(int id)" isn't an object. It *could* be the header for a constructor of a class, however:

Also notice that the above code does not have any objects at all. It defines a class with a constructor. Think of a class as an outline for creating an object. It defines the state with member variables and what can be done with objects of the class with member methods.

An object on the other hand is an instance of a class. You can create an object similar to what you gave above:

Here "bar" is the name of a reference to an object that was created from class Foo. We also say that the object has type Foo. Strictly speaking it is not correct to say that the object is named.

To create 10 different objects (and keep references to all of them), you need an array:

To use the elements of this array, you need to use array subscripting:

I hope this helps to answer your question. I suggest that you look up more information on arrays on the Internet or in a textbook.

Keep Coding!

  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!