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.
Related
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.
The Java Tutorial says that the static nested classes are accessed by using the name of the enclosing class like new EnclosingClassNameHere.StaticNestedClassNameHere()
Why would i want to create an instance of a static class at all? Can somebody please explain?
"static" in this case can be misleading. What it really means is that the class can exist independently. Non-static inner classes can't exist without an instance of the enclosing class.
IMO, when you start using an inner class outside the class that it's in, you need to consider moving it and making it its own top level class. There are very few cases where the relationship between the classes is so tightly coupled that you need to keep it as an inner class.
In your code example:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
You're creating a stand-alone instance of StaticNestedClass.
If it wasn't static, you couldn't do that. You could only create instances of StaticNestedClass() from an instance of OuterClass.
If you moved it to its own .java file, you could treat it nearly identically:
StaticNestedClass notNestedAnymore = new StaticNestedClass();
As to your real question: Why would you want to create an instance of it? For the same reason that you create instances of any class - it does some piece of work that you need.
There is nothing confusing with this code. Static nested class is just a way to introduce yet another namespace.
By creating a static nested class you express very strong relationship between outer and inner class. Typically nested class is a helper or a part of the outer class. For instance when you create a Tree class, Node class is a good candidate for a nested static class. The Tree.Node clearly explains the purpose of the Node class.
In fact, static keyword usage is consistent with static fields. In both cases you can access static entity without an instance of enclosing class. When it comes to static classes it basically means: "I can create an instance of this static nested class without having an instance of outer class". By default (when static keyword is not used) the nested class becomes inner class. In this case you cannot simply write:
new OuterClass.StaticNestedClass();
Instead you are required to pass OuterClass instance with a bit obscure syntax:
OuterClass outerClassInstance = new OuterClass();
outerClassInstance.new InnerClass();
Fortunately when new InnerClass() is executed inside an OuterClass body, this is implictly used as enclosing instance.
In java inner classes have an implicit reference to an instance of the outer class. This way you can access members of the outer class directly, which is usefull in annonymous classes used for callbacks.
class A{
private int a = 3;
class Inner{
Inner(){
System.out.println(a);//also A.this.a
}
}
static class StaticInner{
StaticInner(){
System.out.println(a);//FAILS
}
}
}
Declaring an inner class static simply removes this implicit reference and that is the only difference between static and non static inner classes.
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.
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.