This question already has answers here:
Java inner class and static nested class
(28 answers)
Closed 9 years ago.
What is the difference between static and non-static nested class?
An inner class, by definition, cannot be static, so I am going to recast your question as "What is the difference between static and non-static nested classes?"
A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.
Let's look in the source of wisdom for such questions: Joshua Bloch's Effective Java:
Technically, there is no such thing as a static inner class. According to Effective Java, the correct terminology is a static nested class. A non-static nested class is indeed an inner class, along with anonymous classes and local classes.
And now to quote:
Each instance of a non-static nested class is implicitly associated
with an enclosing instance of its containing class... It is possible
to invoke methods on the enclosing instance.
A static nested class does not have access to the enclosing instance. It uses less space too.
There are two differences between static inner and non static inner classes.
In case of declaring member fields and methods, non static
inner class cannot have static fields and methods.
But, in case of static inner class, can have static and non static fields
and method.
The instance of non static inner class is created with the reference
of object of outer class, in which it has defined, this means it has
enclosing instance. But the instance of static inner class is
created without the reference of Outer class, which means it does
not have enclosing instance.
See this example
class A
{
class B
{
// static int x; not allowed here
}
static class C
{
static int x; // allowed here
}
}
class Test
{
public static void main(String… str)
{
A a = new A();
// Non-Static Inner Class
// Requires enclosing instance
A.B obj1 = a.new B();
// Static Inner Class
// No need for reference of object to the outer class
A.C obj2 = new A.C();
}
}
Static inner class cannot access non-static members of enclosing class. It can directly access static members (instance field and methods) of enclosing class same like the procedural style of getting value without creating object.
Static inner class can declare both static and non-static members. The static methods have access to static members of main class. However, it cannot access non-static inner class members. To access members of non-static inner class, it has to create object of non-static inner class.
Non-static inner class cannot declare static field and static methods. It has to be declared in either static or top level types. You will get this error on doing so saying "static fields only be declared in static or top level types".
Non-static inner class can access both static and non-static members of enclosing class in procedural style of getting value, but it cannot access members of static inner class.
The enclosing class cannot access members of inner classes until it creates an object of inner classes. IF main class in accessing members of non-static class it can create object of non-static inner class.
If main class in accessing members of static inner class it has two cases:
Case 1: For static members, it can use class name of static inner class
Case 2: For non-static members, it can create instance of static inner class.
Discussing nested classes...
The difference is that a nested class declaration that is also static can be instantiated outside of the enclosing class.
When you have a nested class declaration that is not static, Java won't let you instantiate it except via the enclosing class. The object created out of the inner class is linked to the object created from the outer class, so the inner class can reference the fields of the outer.
But if it's static, then the link does not exist, the outer fields cannot be accessed (except via an ordinary reference like any other object) and you can therefore instantiate the nested class by itself.
static inner class: can declare static & non static members but can only access static members of its parents class.
non static inner class: can declare only non static members but can access static and non static member of its parent class.
An inner class cannot be static, so I am going to recast your question as "What is the difference between static and non-static nested classes?".
as u said here inner class cannot be static... i found the below code which is being given static....reason? or which is correct....
Yes, there is nothing in the semantics of a static nested type that would stop you from doing that. This snippet runs fine.
public class MultipleInner {
static class Inner {
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Inner();
}
}
}
this is a code posted in this website...
for the question---> Can a Static Nested Class be Instantiated Multiple Times?
answer was--->
Now, of course the nested type can do its own instance control (e.g. private constructors, singleton pattern, etc) but that has nothing to do with the fact that it's a nested type. Also, if the nested type is a static enum, of course you can't instantiate it at all.
But in general, yes, a static nested type can be instantiated multiple times.
Note that technically, a static nested type is not an "inner" type.
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.
Related
Java The Complete Reference says
A static nested class is one that has the static modifier applied. Because it is static, it must access the non-static
members of its enclosing class through an object. That is, it
cannot refer to non-static members of its enclosing class
directly. Because of this restriction, static nested classes are
seldom used.
What does it mean by "through an object", and "cannot ... directly"?
Java in a Nutshell says
• A static member type can access (only) the static members of the class that contains it.
• A static member type has access to all the static members (including any other static member types) of its
containing type.
Are the two sentences redundant to each other? What are the differences between the two sentences?
Do the quotes from the two books contradict each other? The first
quote says a static nested class can access non-static member of the
enclosing class, while the second quote says a static member type
can access only the static members of the enclosing class.
Thanks.
In Java nested non - static classes have a hidden reference to the instance of the parent class. That's why they can access all non-static members. The nested class doesn't have such an instance. However, its scope allows it to access the parent members if the parent class passes this.
So what the second quote is saying that the access doesn't happen automatically. You pass the reference to the enclosing class and the nested static class can access it. Otherwise, it doesn't know the address of the enclosing class.
No static method may access an instance field directly without first qualifying it with an object of the containing class.
class Foo {
int myField;
public void main(String[] args) {
Foo foo = new Foo();
access(foo);
}
public static void access(Foo obj) {
System.out.println(myField); // <-- error, can't access myField from static
//context.
System.out.println(obj.myField); // OK here
}
}
The same is true for accessing instance fields via inner static classes.
A java static nested class can access the static members of the nested class and the static members of the parent class. This makes sense when you understand the position of a class and object in memory – that there is only one class but multiple objects and you need to decide what each instance of an object needs absolutely necessarily and what is actually redundant and can stay in the class (doesn't need to be duplicated), so all methods (static and non static) and all static members
What members of the enclosing class can a static nested class access?
You can gain clarity to the answer for this question by assigning the following meaning for the Java keyword static:
"Static" in Java means without regard for or association with any instance of any class.
A static field belongs to the class in which it is declared and is not encapsulated by any instance of that class. Any instance of the class that is subsequently constructed (or any instance or any method of any class that is in scope) can access the static field (this is why static fields can be dangerous in concurrent environments).
A static method is defined for the class in which it is declared and has no associated instance of that class. A static method knows of no class instances and can not access any of them unless a reference to an instance is passed to it as an argument.
A static member class is in every way that matters the same as an ordinary top level class that has been packaged within an enclosing class for packaging convenience. Just like a top level class, its instances know nothing of any instance of the enclosing class (unless a reference to an enclosing class instance is passed to them during construction).
A static initializer block is used to initialize static fields for a class, but it knows nothing of any instances of that class. Therefore, they cannot initialize instance fields since they cannot access them.
Therefore, the answer becomes intuitive: a static nested class can access all members of an enclosing class that can be accessed without an instance of that class.
If an enclosing class instance is passed to the static nested class's constructor, then the members of that instance (including the private ones) will be in scope. Logically, passing an enclosing class instance to a static nested class constructor is very similar to using a nested member class. The difference is that for the former, the association is an explicit dependency injection; whereas for the latter, the association between instances is implicit.
I have a class say A, and a static nested class say B.
public class A {
public static class B {
B(Temp x) {
x.reg(this); // need to pass the nested class reference.
}
}
}
Is the above code correct? Can we use this keyword inside nested static class constructor?
Please help me on this. Thanks.
yes, it is. For the runtime, inner classes are just another, separate class. If the inner class is not static it will just have a reference to the outer class, but in your case it's static so not even, so it is exactly as if you created a new class in a new file
Just make sure that you write "public", not "Public"
1) Nested static class doesn’t need reference of Outer class, but Non-static nested class or Inner class requires Outer class reference.
2) Inner class(or non-static nested class) can access both static and non-static members of Outer class. A static class cannot access non-static members of the Outer class. It can access only static members of Outer class.
3) An instance of Inner class cannot be created without an instance of outer class and an Inner class can reference data and methods defined in Outer class in which it nests, so we don’t need to pass reference of an object to the constructor of the Inner class. For this reason Inner classes can make program simple and concise.
for More information please refer this http://www.geeksforgeeks.org/static-class-in-java/
The behavior of the static class in just like a static method. This class belongs to the class but not the instance. Hence, this has no meaning in the static context.
This question already has answers here:
Static nested class in Java, why?
(14 answers)
Closed 9 years ago.
I have been studying about static inner class in java. But i am not clear whats the point of using static inner class or inner class.
class A{
static class B{
}
public static void main(String[] args) {
B b=new B();
}
}
or
class B{}
class A{
public static void main(String[] args) {
B b=new B();
}
}
Non-static inner classes have an automatic reference to their enclosing class. A static inner classes only relationship to its enclosing class is that you have to reference it via the enclosing class' name: EnclosingClass.StaticInnerClass.
Non-static inner classes are good when you want to reference some of the data from the parent class.
A static inner class is good when you just want to associate the inner class with the enclosing class without dragging it along for the ride.
In other words, a non-static inner class can prevent the enclosing class from being garbage collected, since it has that reference, while a static inner class will never do that.
There is technical difference:
class A {
private static int x = 42; //the answer
public static class B {
int showX() {
return x; // only static class can it
}
}
}
But it isn't the main point. If class B is used only by class A it's good to make it inner because some classes in one package may want to have utility class with same name.
The result is the same, but if B is a little Class that A uses it just makes more sense to put it into A.
By making a nested classes can be static, you can use the nested class without having an instance of the outer class.
A nested class is a member of its enclosing 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.
...
Note: 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.
See tutorial here
When your inner class is considered as part of your "object", use inner class.
Indeed, you would be able to access private,package,protected and public fields from your wrapping class.
"Drawback" is: An inner class can't exist without it's wrapping class instantiated, that is logically due to the first sentence.
Otherwise, if you consider:
The behaviour of your nested(called also static inner) class isn't considered as reusable by external class since maybe too specific.
some related fields of one class as being so much related that you want to make
a class wrapping them. This will get your code more understandable and cleaner.
then choose to make a static class.
Moreover, since static (meaning outside the life cycle of any object), a nested class may instantiate without regarding its wrapping class/object.
Why can't a java nested Interface be non-static ? And why can't an inner class contain static non final members ?
I came across the questions while going through Gosling and haven't been able to figure out the answer yet.
If an nested class is non-static (i.e. an inner class), this means that each instance of it is bound to an instance of the outer class. As an interface has no instances of its own, it seems to not be useful for the implementing classes to be bound to an outer object, so having it static by default seems reasonable.
I'm not sure why you can't have static non final members in an inner class but since static members aren't bound to any particular object instance it makes no difference whether it is in the inner or outer class.
E.g.
class OuterClass {
private static int staticMember;
class InnerClass {
void incStatic() {
staticMember++;
}
}
}
You can access the static member from the inner class as if it were within the inner class.
All the crazy Java scoping rules are making my head spin and the public static void nonsense isn't helping matters. So far all the programming languages I have used either lexical scoping or some approximation of it without any access modifiers, i.e. inner stuff captures outer stuff and has access to the outer stuff as long as the inner stuff exists.
So how do I make sense of the scoping rules for inner classes in Java? Do they get access to variables declared in the outer class or is there some weird edge cases I have to worry about because of all the public static private stuff floating around?
Static nested classes1 are exactly like external classes except that they have access to all members of the outer class, regardless of access qualifier. They exist apart from any instance of the outer class, so need a reference to an instance in order to access any instance variables or non-static methods of the outer class.
Non-static nested classes (called inner classes) come into existence only in the context of an instance of the outer class. When constructed, they have a second this field automatically generated, which you can access from within the inner class using the syntax Outer.this. Each instance of the inner class is enclosed by a single instance of the outer class. Again, all the access privileges of static nested classes apply to inner classes. But since they already have an instance of the outer class available, they can automatically access instance variables and methods of the outer class.
For a nice (and very detailed) discussion of inner classes and access specifiers, you can read through the Inner Class Specification. It describes, among other things, how a nested class gets access to private members of its outer class(es). A gentler read is the Nested Classes tutorial.
An off-topic aside: Suppose you have this class structure:
public class O {
public O() { ... }
public class I { // an inner class
public I() { ... }
...
}
...
}
and you've created an instance of O:
O outer = new O();
Now suppose you want to create an instance of O.I. you can't just use new O.I() because the new instance of I needs to be enclosed by a specific instance of O. For this, Java provides the following syntax:
O.I inner = outer.new O.I();
Then inner will then have its second this field set to refer to outer.
Note that this "qualified new operator" syntax is only used for inner classes; it would be unnecessary (in fact, an error) if I were a static nested class.
1 You'll often come across the phrase "static inner class" (including, embarrassingly, in an earlier version of this answer). This is incorrect terminology. In Java, "inner classes" are specifically non-static nested classes.
You have to differenciate:
Static inner classes have access to all static members outside their declaration.
Instance inner classes have access to all class members outside their declaration, AND to final fields in the function they are declared in.
Have in mind that a non-static inner class also has a hidden variable with the instance of the outer class, to access the members there. And that all referenced final fields (therefore they must be final) are copied into the inner class in other hidden member variables when the inner class is instantiated.
Example:
public void doStuff(final int a, int b) {
final int c; // Can be referenced
int d; // Cannot be referenced, not final
executer.execute( new Runnable() {
public void run() {
System.out.println("a: "+a+" c: "+c);
}
}
b++; // Not final, not referencable
System.out.println(b);
}
I don't know if it helps, but from the java tutorials:
Static Nested Classes
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.
Note: 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.
Inner Classes [Non-Static Nested class?]
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.
You should check the java tutorial on nested classes.
Rules of the Inner classes in Java
In Java it is possible to define a class inside another class such classes are called nested classes or inner class.
There are 3 types of the Inner classes Instance Inner class, static inner class and anonymous inner class
If the Inner class is declared as instance inner class then it can access all of the members of the outer enclosing class including private members
If the Inner class is declared as static then it can only access the static members of the outer class (including the private static members). But it can NOT access the instance members
Consider that there is a variable x is defined in both the outer class and the instance inner classes then general form for accessing the variable from the inner class is this.x for the inner x and OuterClassname.this.x for the outer x.
You can also define an inner class inside any method or any other block
The general form for instantiating the inner class from outside the outer class is
Outer.Inner ob = new Outer.new Inner();
The general form for instantiating the inner class from outside the outer class is (if the inner class is declared as static)
Outer.Inner ob = new Outer.Inner();
The Inner classes can be declared with any of the access modifier keywords
If the Inner class is declared as private then it can NOT be instantiated from outside the outer class. Also in this case you can NOT access the members of the Inner class from outside the outer class even you have an object reference and even if the members of the private inner class are declared as public.
If the Inner class is declared as instance inner class then it can also access the superclass members of the outer class through the general statement
Outer.super.variable; Outer.super.method(params);
Rules for inner class
Outer class accessed by inner class
Inner class can't be accessed by outer class
The inner class members only used the methods and members within the class only access the fulled information
Method Scoped inner classes:-
Can only access the final members of the outer class.