Nested class in interface java

Inner class in interface vs in class

What is the difference between these two innerclass declarations? Also comment on advantages/disadvantages? case A: class within a class.

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.

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.

I am not looking for semantics of whether it is called inner or nested class. I am looking for feature differences.

@h2g2 — after only reformatting the code — you second example is incorrect, you can’t have an implemented method in an interface. Or maybe the curly brackets were not at their right places.

Читайте также:  Sign Up

For the interface definition you have shown I get a compile error(both with JDK/5 and 6) «interface methods cannot have body». Did you copy/paste your code that compiles or just typed it ?

personally, i don’t like public inner classes at all. if they’re only used by one class i make them private, if they’re used by multiple classes, they deserve their own namespace. i also would never create an inner class within an interface. i wouldn’t want/expect it to work like that, but have never bothered to test.

6 Answers 6

An static inner class is a nested class, and the non-static is called an inner class. For more, look here.

However, I like to quote an excerpt from the same link.

A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

You didn’t use the word static in the second case. And you think it would implicitly be static because its an interface. You are right in assuming that.

You can instantiate the inner class in your interface, just like a static nested class, because its really a static nested class.

Levels.Items hello = new Levels.Items(); 

So, the above statement will be valid in both of your cases. Your first case is of static nested class, and in the second case you didn’t specify static , but even then it would be an static nested class because its in the interface. Hence, no difference other then the fact that one is nested in a class, and the other in an interface.

Normally an inner class in a class, not in interface, would be instantiated like below.

Levels levels = new Levels(); Levels.Items items = levels.new Items(); 

Moreover, a «non-static» inner class will have a implicit reference to its outer class. This is not the case with «static» nested class.

Wlements in an interface are static so the second case is also a static class. Please note the question is one is enveloped by a class while the other enveloped by an interface. The question is what is the behavioral differences between embedding a static class in a class vs in an interface.

Static inner classes are mostly similar to top-level classes, except the inner class has access to all the static variables and methods of the enclosing class. The enclosing class name is effectively appended to the package namespace of the inner class. By declaring a class as a static inner class, you are communicating that the class is somehow inseparably tied to the context of the enclosing class.

Non-static inner classes are less common. The main difference is that instances of a non-static inner class contain an implicit reference to an instance of the enclosing class, and as a result have access to instance variables and methods of that enclosing class instance. This leads to some odd looking instantiation idioms, for example:

Levels levels = new Levels(); // first need an instance of the enclosing class // The items object contains an implicit reference to the levels object Levels.Items items = levels.new Items(); 

Non-static inner classes are much more intimately tied to their enclosing classes than static inner classes. They have valid uses (for example iterators are often implemented as non-static inner classes within the class of the data structure they iterate over).

It’s a common mistake to declare a non-static inner class when you only really need the static inner class behaviour.

If you declare a nested class in an interface it is always public and static. So:

I’ve checked this with javap -verbose and they all produce

Compiled from "Levels.java" public class Levels$Items extends java.lang.Object SourceFile: "Levels.java" InnerClass: public #14= #3 of #23; //Items=class Levels$Items of class Levels minor version: 0 major version: 50 Constant pool: const #1 = Method #4.#21; // java/lang/Object."":()V const #2 = Field #3.#22; // Levels$Items.value:Ljava/lang/String; const #3 = class #24; // Levels$Items const #4 = class #25; // java/lang/Object const #5 = Asciz value; const #6 = Asciz Ljava/lang/String;; const #7 = Asciz path; const #8 = Asciz ; const #9 = Asciz ()V; const #10 = Asciz Code; const #11 = Asciz LineNumberTable; const #12 = Asciz LocalVariableTable; const #13 = Asciz this; const #14 = Asciz Items; const #15 = Asciz InnerClasses; const #16 = Asciz LLevels$Items;; const #17 = Asciz getValue; const #18 = Asciz ()Ljava/lang/String;; const #19 = Asciz SourceFile; const #20 = Asciz Levels.java; const #21 = NameAndType #8:#9;// "":()V const #22 = NameAndType #5:#6;// value:Ljava/lang/String; const #23 = class #26; // Levels const #24 = Asciz Levels$Items; const #25 = Asciz java/lang/Object; const #26 = Asciz Levels; < public java.lang.String value; public java.lang.String path; public Levels$Items(); Code: Stack=1, Locals=1, Args_size=1 0: aload_0 1: invokespecial #1; //Method java/lang/Object."":()V 4: return LineNumberTable: line 2: 0 LocalVariableTable: Start Length Slot Name Signature 0 5 0 this LLevels$Items; public java.lang.String getValue(); Code: Stack=1, Locals=1, Args_size=1 0: aload_0 1: getfield #2; //Field value:Ljava/lang/String; 4: areturn LineNumberTable: line 7: 0 LocalVariableTable: Start Length Slot Name Signature 0 5 0 this LLevels$Items; > 

Источник

Where it is useful to have nested classes in an interface? [duplicate]

But it boiled down to same problem that why not use it as a just another class. What the difference or value addition with this approach ?

Whenever you want to be sure the classes implementing your interface have access to said class with a certain implementation.

@SubodhJoshi The linked helped .My Question also asked to let me know how I can invoke the class method .

2 Answers 2

You can create an instance of ifaceClass inside the class that implements Iface :

interface Iface < void show(); class ifaceClass < int x; public ifaceClass() < System.out.println(x); >> > public class Test implements Iface < public static void main(String args[]) < ifaceClass iface = new ifaceClass(); >@Override public void show() < // . >> 

If the class doesn’t implement the interface, just create an instance like this:

Iface.ifaceClass iface = new Iface.ifaceClass(); 

Why create a class inside an interface? Basically for the same reason you create a class inside another class, to group related classes together.

Where it is useful to have nested classes in an interface?

There is no such case which can only be fulfilled with inner class of interface. It is syntactically valid to have inner class in interface and for the class which implement interface can create instance of class and apart from that Interface.Class can also make that class accessible because it can not be private at all.

I noticed if Test has not implemented the Iface then I needed following import import com.jls.Iface.ifaceClass;

Not necessarily, if your interface is accessible your inner class will automatically become accessible.Here you are trying to access class directly without even importing interface in that case following statement need above import statement.

ifaceClass ifaceClassObj = new ifaceClass(); 

But it boiled down to same problem that why not use it as a just another class. What the difference or value addition with this approach

Exactly, creating another class can also provide you the same facility and I have never seen any use case in my day to day programming which can only be fulfilled with inner class of interface.It does not provide anything else than accessibility through the interface.

I have used it once which I think quite a bad practice though. One day we need to implement one common method in different classes which are implementing interface say X and we wanted to add one extra method to be used by all this classes to add one kind of check on the Object which only check some parameter and return boolean even though that use case can be fulfilled in other way but to be specific that it is only intended for classes which are implementing this interface we have added class in interface so that we can provide that method to implementing classes.(NOTE : Nowadays default method can be used in this case instead of inner class)

Here, it is wise to note that in huge projects it is quite impossible for anyone ( other than creator ) to note that any interface has inner class. So, until we implement that class or manually check the interface we can not came to know that interface has inner class.

Источник

Why does Java allow nested class definitions in an interface?

I’m actually wondering on when a class in an interface would be beneficial from a OO/Acrhitectural/Structural point of view ? Why does Java allow this ?

Actually, some people have asked why there are not fewer restrictions. (The answers are the same: that’s just the way Java decided.)

@Radiodef sure, of course , but I’m actually looking for someone who knows the reason behind the decision (I understand that this is unlikely, unless he’s a Java dev/designer), or a case where he/she used it and it was beneficial.

1 Answer 1

From what I remember in «Thinking in Java» B. Eckel showed it as relict which could be used to place in interface class with some static methods which could for example be tests of correct implementation of interface, for instance

interface SomeList < T get(int i); void add(T t); int size(); class FewTests< //some very bad test, but remember that this is just example static boolean simpleTest1(SomeList list, T t) < int before = list.size(); list.add(t); return list.size() - before == 1; >> > 

@Radiodef so you think this is probably just an outdated feature that is just there for backward compatibility (this is actually my belief) ?

@Simeon What I am saying is obsolete is the example in the answer. Java 8 allows static methods on interfaces. I am chiding Pshemo a little because if this is the kind of answer you are looking for then your question is probably off-topic. There are 100 answers like this.

@Radiodef What you are saying is true. Originally I was meant to post it as comment but I couldn’t add code in nice form to it so decided to post it as answer.

Yeah, OK, I’m not trying to bug you. I would just hate to see a question like this get bombarded by 100 «here’s 1 way you can use it» answers when there could be a historical reason somebody knows about.

Источник

Inner class within Interface

Is it possible to create an inner class within an interface?
If it is possible why would we want to create an inner class like that since we are not going to create any interface objects? Do these inner classes help in any development process?

13 Answers 13

Yes, we can have classes inside interfaces. One example of usage could be

public interface Input < public static class KeyEvent < public static final int KEY_DOWN = 0; public static final int KEY_UP = 1; public int type; public int keyCode; public char keyChar; >public static class TouchEvent < public static final int TOUCH_DOWN = 0; public static final int TOUCH_UP = 1; public static final int TOUCH_DRAGGED = 2; public int type; public int x, y; public int pointer; >public boolean isKeyPressed(int keyCode); public boolean isTouchDown(int pointer); public int getTouchX(int pointer); public int getTouchY(int pointer); public float getAccelX(); public float getAccelY(); public float getAccelZ(); public List getKeyEvents(); public List getTouchEvents(); > 

Here the code has two nested classes which are for encapsulating information about event objects which are later used in method definitions like getKeyEvents(). Having them inside the Input interface improves cohesion.

Yes, you can create both a nested class or an inner class inside a Java interface (note that contrarily to popular belief there’s no such thing as an «static inner class«: this simply makes no sense, there’s nothing «inner» and no «outter» class when a nested class is static, so it cannot be «static inner»).

Anyway, the following compiles fine:

I’ve seen it used to put some kind of «contract checker» directly in the interface definition (well, in the class nested in the interface, that can have static methods, contrarily to the interface itself, which can’t). Looking like this if I recall correctly.

Note that I’m not commenting on the usefulness of such a thing, I’m simply answering your question: it can be done and this is one kind of use I’ve seen made of it.

Now I won’t comment on the usefulness of such a construct and from I’ve seen: I’ve seen it, but it’s not a very common construct.

200KLOC codebase here where this happens exactly zero time (but then we’ve got a lot of other things that we consider bad practices that happen exactly zero time too that other people would find perfectly normal so. ).

Источник

Оцените статью