Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concept Behind Static classes in Java

Consider the following code

class A {
    static class B{
        int a = 0;
    }
    public static void main(String argc[]) {
        B var1 = new B();
        B var2 = new B();
        var1.a = 5;
        var2.a = 6;
        System.out.println(var1.a+" and "+var2.a);
    }
}

It outputs 5 and 6. Static members are loaded only once.But the output contradicts with that statement.So surely the concept of static classes is different from static data members.So what does static mean in case of static classes

like image 384
Jinu Joseph Daniel Avatar asked Nov 04 '12 20:11

Jinu Joseph Daniel


2 Answers

A copy paste from oracle:

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. Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject =
     new OuterClass.StaticNestedClass();

An example:

There is no need for LinkedList.Entry or Map.Entry to be top-level class as it is only used by LinkedList aka Map. And since they do not need access to the outer class members, it makes sense for it to be static - it's a much cleaner approach.

like image 171
Frank Avatar answered Sep 28 '22 04:09

Frank


Static, in case of classes, means that they are not related to an instance of their outer class:

class A{
  class B{
    ...
  }
}
...
new A.B(); //error

is invalid. Because B is not static, it holds an implicit reference to an instance of A. This means you cannot create an instance of B without an instance of A.

class A{
  static class B{
    ...
  }
}
...
new A.B();

is perfectly valid. Since B is static, it doesn't hold a reference to A, and can be created without an instance of A existing.

Static class is a class that doesn't hold an implicit reference to its enclosing class. Static class behaves just like an ordinary class except its namespace being within another class.

Non-static inner class holds an implicit reference to its enclosing class. The enclosing class' variables are directly accessible to an instance of the inner class. A single instance of the outer class can have multiple instances of its inner class(es).

like image 24
John Dvorak Avatar answered Sep 28 '22 02:09

John Dvorak