Can a class in Java be static? The answer is yes. In Java we can have static instance variables, static methods, static blocks. The class can also be static.
Java allows us to define static classes within a class. such as the inner class (nested classes). The class enclosing the nested class is called an external class. In Java, we cannot decorate the top level class with Static. Only the inner class can be static.
What is the difference between a static inner class and a non-static inner class? Here are the main differences between the two.
(1) Internal static classes do not need to have references to external classes. But non-static inner classes need to hold references to the external class.
(2) non-static inner classes can access static and non-static members of external classes. Static classes cannot access non-static members of external classes. He can only access static members of external classes.
(3) A non-static inner class cannot be created from an external class entity, and a non-static inner class can access the data and methods of the external class, because he is inside the outer class.
Based on the above discussion, we can make programming simpler and more efficient through these features.
/*The following procedure shows how to create a static inner class and a non-static inner class in Java*/classouterclass{Private StaticString msg = "Geeksforgeeks"; //static inner class Public Static classnestedstaticclass{//static inner classes can only access static members of external classes Public voidPrintmessage () {//try to change msg to non-static, which will result in a compilation errorSystem.out.println ("Message from nested static class:" +msg); } } //non-static inner class Public classinnerclass{//Either static or non-static methods can be accessed in non-static inner classes Public voiddisplay () {System.out.println ("Message from Non-static nested class:" +msg); } }} classmain{//How to create an instance of a static inner class and a non-static inner class Public Static voidMain (String args[]) {//to create an instance of a static inner classOuterclass.nestedstaticclass printer =NewOuterclass.nestedstaticclass (); //to create a non-static method of a static inner classPrinter.printmessage (); //in order to create a non-static inner class, we need an instance of the outer classOuterclass outer =NewOuterclass (); Outerclass.innerclass Inner= Outer.NewInnerclass (); //non-static methods that call non-static inner classesInner.display (); //We can also combine the above steps to create an inner class instance in one stepOuterclass.innerclass InnerObject =NewOuterclass ().NewInnerclass (); //also we can now invoke the inner class methodInnerobject.display (); }}
Reference links
Http://stackoverflow.com/questions/7486012/static-classes-in-java
The static class in Java