What does the 'new' keyword actually do in Java, and should I avoid creating new objects?

前端 未结 6 1347
盖世英雄少女心
盖世英雄少女心 2020-11-28 10:15

I signed up a few moments ago, though I\'ve been making great use of this site since I took up computer programming, which I\'ve been teaching myself and consider a little h

6条回答
  •  情书的邮戳
    2020-11-28 10:56

    Now, suppose I invoke myMethod(), say, 10 times while running my program, how does that work? Is a new object create every time?

    Yes!

    Reusing or not reusing an instantiated object depends on the design and situation. There are cases where it's better to reuse objects, in which case you can create a class field to hold on to the reference, and there are cases where it's best to create a new object every time(look into immutability, for instance).

提交回复
热议问题