简体   繁体   中英

Object creation at class level

public class DoSomething { private static final Logger logger = LoggerFactory.getLogger(DoSomething.class);

private final AtomicBoolean Flag = new AtomicBoolean(false);

LogMessage logMessage= new LogMessage(); // Creating an object to call a method in it

public static final String ERROR_MAP = "ERROR_MAP";
public static final String errorJsonString = System.getenv("RESTART_ERROR_MAP");

I tried to create an object of LogMessage. And use it inside a method of DoSomething class. Is this fine or should I move that line inside the method?

You haven't told us much about your LogMessage class. However, in general:

  • you should try to declare variables as close as possible to where they're first used.
  • you should try to instantiate class instances when you declare the class variable.
  • you should try to restrict the visibility of a variable to only that area of the code wehre it's used.

If you're only using LogMessage inside a method... and if you're not going to re-use that instance across different method invocations... I'd suggest you declare and initialize it inside the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM