Walkerbo Walkerbo - 6 months ago 22
Java Question

Java - Inner Classes

I am trying to work with inner classes and I some questions about them
I have a gameObject class as follows

import java.io.*;
public abstract class GameObject implements Serializable {
protected enum GAME_OBJECT_TYPE {SNARK, HINT, BONUS_ITEM, INVALID};
protected GAME_OBJECT_TYPE eGameObjectType;
protected GameObject() {
eGameObjectType = (GAME_OBJECT_TYPE.INVALID);
System.out.println("SOMETHING WENT WRONG");
}
public class Snark extends GameObject implements Serializable {
public Snark() {
eGameObjectType = (GAME_OBJECT_TYPE.SNARK);
System.out.println("SNARK LIVES HERE");
}
}
public class Hint extends GameObject implements Serializable {
public Hint() {
eGameObjectType = (GAME_OBJECT_TYPE.HINT);
System.out.println("HINT LIVES HERE");
}
}
}


With this GameObject class structure I get no errors but the only way I can instantiate a Snark in my GameFrame without errors is

GameObject mySnark = new GameObject.Snark(); // all good
GameObject mySnark = new Snark(); // cannot be resolved


However when I change the gameObject class to

import java.io.*;
public abstract class GameObject implements Serializable {
protected enum GAME_OBJECT_TYPE {SNARK, HINT, BONUS_ITEM, INVALID};
protected GAME_OBJECT_TYPE eGameObjectType;
protected GameObject() {
eGameObjectType = (GAME_OBJECT_TYPE.INVALID);
System.out.println("SOMETHING WENT WRONG");
}
}
public class Snark extends GameObject implements Serializable { // The public type Snark must be defined in its own file
public Snark() {
eGameObjectType = (GAME_OBJECT_TYPE.SNARK);
System.out.println("SNARK LIVES HERE");
}
}
public class Hint extends GameObject implements Serializable {
public Hint() {
eGameObjectType = (GAME_OBJECT_TYPE.HINT);
System.out.println("HINT LIVES HERE");
}
}


I can now instantiate a Snark in my GameFrame as

GameObject mySnark = new Snark(); // no errors


I can re-split each object into its own class again but it thought this may be a way to greatly reduce the number of classes that I currently have.

Can someone help me understand what I have got wrong?

Thank you

Answer

Inner classes are not meant to reduce number of classes in your project (as your question suggests); it's about logically grouping functionality to a certain parent class, most commonly for helper classes specific to the parent class. Inner classes would also typically not extend their containing parent class.

Per your example, there appears to be a need to instantiate objects of type Snark outside of GameObject, which suggests Snark should be an independent class.

More info on inner classes from Oracle's JavaDoc.

Comments