Can classes in java be static? The answer is yes. In Java we can have static instance variables, static methods, and static blocks. Classes can also be static.
Java allows us to define static classes in a class. For example, nested class. The class that enclosed nested class is called an external class. In Java, we cannot modify top level class with static. Only inner classes can be static.
What is the difference between static inner classes and non-static inner classes? Here are the main differences between the two.
(1) The internal static class does not need to have a reference to the external class. But non-static inner classes need to hold references to external classes.
(2) Non-static inner classes can access static and non-static members of external classes. A static class cannot access non-static members of an external class. It can only access static members of external classes.
(3) A non-static inner class cannot be created without the external class entity, and a non-static inner class can access the data and methods of the external class because it is inside the external class.
Based on the above discussion, we can make programming easier and more effective through these features.
/* The following program shows how to create static inner classes and non-static inner classes in java*/class OuterClass{ private static String msg = "GeeksForGeeks"; // Static inner class public static class NestedStaticClas s{ // Static inner class can only be accessed static member of the external class public void printMessage() { // Try to change msg to non-static, which will cause the compilation error System.out.println("Message from nested static class: " + msg); } } // Public class InnerClass{ // Whether it is a static method or a non-static method, public void display(){ System.out.println("Message from non-static nested class : "+ msg); } }} class Main{ // How to create instances of static inner classes and non-static inner classes public static void main(String args[]){ // Create instances of static inner classes OuterClass.NestedStaticClass printer = new O uterClass. NestedStaticClass(); // Create a non-static method of static inner class printer.printMessage(); // In order to create a non-static inner class, we need an instance of the outer class OuterClass outer = new OuterClass(); OuterClass.InnerClass inner = outer. new InnerClass(); // Call the non-static method inner.display() of the non-static inner class; // We can also use the above steps to create an internal class instance OuterClass.InnerClass innerObject = new OuterClass().new InnerCla ss( ); // Similarly, we can now call the inner class method innerObject.display(); }}The above content is the relevant information about the editor introducing Static Class in Java to you. I hope it will be helpful for everyone to learn static class in Java.