Alex Rivera | Logout

Inner class in interface vs in class

Asked 2009-12-04T09:00:09.167
28

What is the difference between these two innerclass declarations? Also comment on advantages/disadvantages?

case A: class within a class.

public class Levels {   
  static public class Items {
    public String value;
    public String path;

    public String getValue() {
      return value;}
  }
}

and case B: class within interface.

public interface Levels{

  public class Items {
    public String value;
    public String path;

    public String getValue() {
      return value;}
  }
}

Made correction: to placement of getvalue method.

further info: I am able to instantiate Items class in both cases A and B in another class that does not implement interface AT ALL.

public class Z{//NOTE: NO INTERFACE IMPLEMENTED here!!!!
 Levels.Items items = new Levels.Items();
}

Since an interface is not instantiated, all the elements inside an interface are accessible by dot notation without LEVELS interface instantiated simply because you cannot instantiate an interface - effectively making a class defined inside an interface permeable to static reference.

So saying that Items class in case B is not static does not make sense. Since both cases A and B are instantiated the same way, I am not looking for semantics on what is static or inner or nested. Stop giving me answers on semantics. I want the compiler, runtime and behavioural differences/advantages, or if none then say so. No more answers on semantics please!!!!! An expert on JVM or .NET VM specification innards please this answer question rather than text book semanticissiests.

Edit
Report

1 Answer

7

The examples you give of nested / inner classes are (IMO) bad examples. Besides the 2nd example is not valid Java since an interface can only declare (implicitly) abstract methods. Here's a better example:

public interface Worker {

    public class Response {
        private final Status status;
        private final String message;
        public Response(Status status, String message) {
            this.status = status; this.message = message;
        }
        public Status getStatus() { return status; }
        public String getMessage() { return message; }
    }

    ...

    public Response doSomeOperation(...);
}

By embedding the Response class, we are indicating that it is a fundamental part of Worker API with no other uses.

The Map.Entry class is a well-known example of this idiom.

answered 2009-12-04T09:40:23.547

Your Answer