Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Static Classes In Java

Is there anything like static class in java?

What is the meaning of such a class. Do all the methods of the static class need to be static too?

Is it required the other way round, that if a class contains all the static methods, shall the class be static too?

What are static classes good for?
by

2 Answers

akshay1995
There is a static nested class, this [static nested] class does not need an instance of the enclosing class in order to be instantiated itself.

These classes [static nested ones] can access only the static members of the enclosing class [since it does not have any reference to instances of the enclosing class...]

code sample:

public class Test {
class A { }
static class B { }
public static void main(String[] args) {
/will fail - compilation error, you need an instance of Test to instantiate A*/
A a = new A();
/*will compile successfully, not instance of Test is needed to instantiate B
/
B b = new B();
}
}
RoliMishra
Yes there is a static nested class in java. When you declare a nested class static, it automatically becomes a stand alone class which can be instantiated without having to instantiate the outer class it belongs to.

Example:

public class A
{

public static class B
{
}
}

Because class B is declared static you can explicitly instantiate as:

B b = new B();

Note if class B wasn't declared static to make it stand alone, an instance object call would've looked like this:

A a= new A();
B b = a.new B();

Login / Signup to Answer the Question.