Can someone please explain the difference between the following cases and where would we use each one?
Thanks all
class A{
static public void methodA()
}
static class B{
static public void methodB()
}
static class C{
public void methodC()
}
Edit:
Hello all thank for the answers. I maybe I was not clear enough. I am aware that classes B and C can not be declared static unless they are inner classes. I so in your answers please assume that they are inner classes. I want to know when would I declare them static and even when to declare their methods static. I know that a static method in a non static class means that you can call it from anywhere and it is generally to perform general operations that are not specific to an object. But why would you declare static class?
I will check your answers again after you reread my edit and accept the most explanatory answer
The static modifier is used to declare static fields or class variables.
Source: “Understanding Instance and Class Members”
Also note that Java supports both static variables and methods. So going by this, your first class would compile correctly, while the other two would fail.
Just to give an example:
There’re some reasons as to why one might want to do that. For example, from this Java Tutorial:
A good example of this is the
static class Entry<K,V> implements Map.Entry<K,V>used in places like the HashMap class.The existence of the Entry class is closely related to the functioning of how HashMap stores/retrieves key/value pair stored as its content. As you can see the Entry class provides functionality only to the HashMap implementation, even though its behaviorally equivalent to a top-level class. So it does make sense to package it as part of the HashMap definition itself.
You can find similar usage with
private static class Entry<E>in the LinkedList implementation.Another reason that I can think of is a way for white-box testing. Since an inner static class has access to the private and protected static variables/methods of the outer class, you can very well use this to test the internal states of the outer class. Some might consider this dirty but then it can sometimes be useful
In my opinion, Static inner classes are mostly for convenience, and are generally based on your design principles.