0

How can I do something like below:

Object a,b,c = new Object ();

i.e. creating multiple objects with different names? Or must they all be created seperately as below?

Object a = new Object ();
Object b = new Object ();
Object c = new Object ();
5
  • you have to use 2nd variant Commented Aug 7, 2018 at 16:55
  • 1
    Nope, no way around "one at a time". Commented Aug 7, 2018 at 16:58
  • Are you sure you also want three variables? Why not creating a container like an array or a List and then looping over it? Please do not use Object in your code if you have something more specific (ignore if it was just for an example). Commented Aug 7, 2018 at 17:33
  • There is also a misconception on your end: you are instantiating objects of the same class, but you are creating three distinct, different objects. When you buy three sheep, you have three different animals, not one! Commented Aug 7, 2018 at 17:48
  • Related, near duplicates: stackoverflow.com/questions/4328339/…, stackoverflow.com/questions/6202818/… and stackoverflow.com/questions/30248287/… Commented Aug 7, 2018 at 18:26

1 Answer 1

5

The shortest way would be

Object a = new Object(), b = new Object(), c = new Object();
int foo=5, bar=9, zzz=7;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.