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 ();
A.Polieshchuk
  • 37
  • 1
  • 5
  • you have to use 2nd variant – Iłya Bursov Aug 07 '18 at 16:55
  • 1
    Nope, no way around "one at a time". – jingx Aug 07 '18 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). – Zabuzard Aug 07 '18 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! – GhostCat Aug 07 '18 at 17:48
  • Related, near duplicates: https://stackoverflow.com/questions/4328339/declare-multiple-java-arrays-on-same-line, https://stackoverflow.com/questions/6202818/initializing-multiple-variables-to-the-same-value-in-java and https://stackoverflow.com/questions/30248287/how-to-define-multiple-variables-in-single-statement – Mark Rotteveel Aug 07 '18 at 18:26

1 Answers1

5

The shortest way would be

Object a = new Object(), b = new Object(), c = new Object();
int foo=5, bar=9, zzz=7;
azro
  • 53,056
  • 7
  • 34
  • 70