I have found code in which static class contains methods that are not declared static. Compiler doesn't display any warning. It seems confusing, doesn't it?
Static class always contains static members. Non-static class may contain both static and non-static methods. Static class does not contain an instance constructor. Non-static class contains an instance constructor.
What is Utility Class? Utility Class, also known as Helper class, is a class, which contains just static methods, it is stateless and cannot be instantiated. It contains a bunch of related methods, so they can be reused across the application.
A static method can call only other static methods; it cannot call a non-static method.
Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables. We can inherit static methods in Java.
The answers here are good, but I guess I should add an example. Consider the following class definition
class Foo{
class Bar{
int x;
}
}
To use the class Bar you'll have to create an instance of class Foo first.
Foo foo = new Foo();
Foo.Bar bar = foo.new Bar();
bar.x = 10;
But if you have used the static keyword like the following
class Foo{
static class Bar{
int x;
}
}
You could have skipped a step
Foo.Bar bar = new Foo.Bar();
bar.x = 10;
If you'll try to statically use Foo.Bar directly when the inner class is not static, then you'll get the following error -
error: an enclosing instance that contains Foo.Bar is required
Foo.Bar bar = new Foo.Bar();
^
1 error
I think this example should clear it.
There is no concept of static class in java (not even static inner class). If you see class is static and it is in working condition then it must be inner class(also called as nested class) which is declared as static. And there is no restriction to have only static methods in static inner classes.
The significance of declaring an inner class static is to be able to create instances of the nested class independent of the class in which it is nested. If static is not mentioned then every instance of the nested class will be associated with an instance of the class in which it is nested.
This question has more details. Java inner class and static nested class
A static class is a nested class which has no implicit reference to the outer class. A static class can have static methods or instance methods. Note: an inner class can't have static methods.
Only inner classes can be declared static
. A static class has no pointer to its outer class and can therefore only refer to static fields and methods of the outer class. A static class may however itself contain non-static methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With