简体   繁体   中英

Java static nested classes in separate files

I'm working on my own game engine and came to a wall that stopped me. When I'll be coding a game I will simply use my gameengine.jar as a library. But I want to reference some classes with a god-class "GameEngine".

In this example I will want to use a class "Logger" that simply logs errors. Both GameEngine and Logger don't have a constructor, they are static.

public class GameEngine{
  public static Logger logger = Logger; // ERROR
}

class Logger{
  static void logError(){
    System.out.println("Error");
  }
}

I want to do GameEngine.logger.logError(); but can't.
I could use a nested class but both classes are very long.

Solution A:

public class Logger{
  public static void logError(){
    System.out.println("Error");
  }
}

And from anywhere in the code then:

Logger.logError();

SOlution B if you want to call it from GameEngine on top:

public class GameEngine{
  public static Logger logger = new Logger();
}

(Meaning the constructor of Logger isn't private)

then from anywhere in the code:

GameEngine.logger.logError();

Standard logging API

There no reason for you to re-implement a logging API while dozen of them exist in Java.

For example there log4j that is well known: https://logging.apache.org/log4j/2.x/manual/api.html

And there also a standard in java to hide the actual logger implementation and provide a common interface ( https://www.vogella.com/tutorials/Logging/article.html )

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