javaoopstaticstatic-classes

Serializing static inner classes java


I'm making a game in Java at the moment and how I am planning on handling NPCs at the moment is having each NPC be an instance of their own unique class, all of which inherit from an abstract NPC class.

For example, if I have a character named 'Michael', Michael will be an instance of the Michael class, which will inherit from NPC.

While I was setting this up, it occured to me that perhaps I could have all the NPC classes defined as static classes within the body of the NPC class, mainly just because I will then only have the NPC.java file, and not a bunch of Michael.java, John.java, etc.

so this would look like

public abstract class NPC implements Seralizable {

   //stuff

   public static class Michael extends NPC {

      //more stuff

   } 

}

and when I need to create an instance of Michael in the game, it would look like

NPC npc1 = NPC.Michael();

As you can see above, NPC implements Seralizable, and this is so I can save the gamestate to a file. My main concern at the moment is if these inner static classes would do anything funny with serialization, as static fields are all transient.

I would also appreciate feedback on this style of organizing the code, and if people would normally just prefer having the classes in their own files


Solution

  • static inner classes are identical to top-level classes in every way other than how they are named. Whether they serialize or not is utterly independent of the class they are inside of. There is no difference, whatsoever, between:

    --- Michael.java:
    
    public class Michael extends Npc { ... }
    
    --- Npc.java
    
    public class Npc implements Serializable { .... }
    

    and

    ---- Npc.java
    
    public class Npc implements Serializable {
      public static class Michael extends Npc { .... }
    }
    

    if Michael is not going to contain any custom code (just inherits from Npc but otherwise doesn't define anything different or new), Michael should not be its own class.