Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the non-syntactic differences between static and non-static inner classes in Java? [duplicate]

Possible Duplicate:
Java inner class and static nested class

An instance of a static inner class cannot access the instance members of its enclosing class, whereas an instance of a non-static inner class can. This is what i mean by syntactic difference. Because whether declaring an inner class to be static determines whether the syntax of your program is correct.

But is there any other difference that's not part of the Java syntax? Let's say class A is a top-level class, and class B is an inner class of A. If I'm not going to access the instance members of A within B, then I should declare B to be static. But since i'm not required to, i could declare B to be non-static and there would be no compilation error. So in this case, is there any difference, probably in the generated bytecode, or any runtime difference?

Thanks!

like image 672
weidi Avatar asked May 19 '12 10:05

weidi


People also ask

What is the difference between a static and non static inner class?

Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

What is the difference between static and non static class in Java?

The static method uses compile-time or early binding. The non-static method uses runtime or dynamic binding. The static method cannot be overridden because of early binding. The non-static method can be overridden because of runtime binding.

What is the main difference between an inner class and a static nested class in Java?

1) First and most important difference between Inner class and nested static class is that Inner class require instance of outer class for initialization and they are always associated with instance of enclosing class. On the other hand nested static class is not associated with any instance of enclosing class.

What is non static class in Java?

A non-static method does not have the keyword static before the name of the method. A non-static method belongs to an object of the class and you have to create an instance of the class to access it. Non-static methods can access any static method and any static variable without creating an instance of the class.


1 Answers

The difference is bigger than that. static inner classes can be created from outside the class, without having an instance of the class, non-static ones cannot.

The fact that you can access enclosing class members is a result of this, because a static inner class is not bound to an instance of the enclosing class, but a non-static one is.

like image 138
Luchian Grigore Avatar answered Oct 15 '22 04:10

Luchian Grigore