2

I want to create an array for each object i create, but i cant get access to it. since its scope is within the constructor.

class Constructor{

Constructor(int vsl)
{
        int[] array = new int[vsl];
    }

}

If i call this constructor by Constructor c = new Constructor(4);

how can i use array in my code?

Note: i want to specifically create the object inside the constructor and manipulate it using values i get from scanner object.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
amarnath harish
  • 945
  • 7
  • 24
  • @Jens "global" isn't a term I would use in a java context – GhostCat Jun 08 '17 at 06:59
  • I advise you to take a look at tutorials on java objects before trying to code one. – MrPromethee Jun 08 '17 at 06:59
  • You made `array` a local *variable* in your constructor; but it needs to be a *field* of your class. Thus: learn about such basics first. You dont learn basics by trial and and error, but by studying tutorials and books. – GhostCat Jun 08 '17 at 07:00
  • I would suggest you to initialize the int array[] outside the constructor and then use it inside – Akshay Jun 08 '17 at 07:00

1 Answers1

2

You can not, that array is scoped and visible only inside of the constructor

what you have to do is declare that array as a member class and initialize it in the constructor:

class Constructor {
    private int[] array;
    Constructor(int vsl) {
        array = new int[vsl];
    }

}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97