I am trying to find why the class cant be created as a static? Like:
public static class Qwert{ public static void main(String args[]){ int x = 12; while(x<12){ x--; } System.out.println(" the X value is : "+ x); } }
We can't declare outer (top level) class as static because the static keyword is meant for providing memory and executing logic without creating Objects, a class does not have a value logic directly, so the static keyword is not allowed for outer class.
The answer is YES, we can have static class in java. In java, we have static instance variables as well as static methods and also static block. Classes can also be made static in Java.
In Java, a static method cannot be abstract.
We can declare a class static by using the static keyword. A class can be declared static only if it is a nested class. It does not require any reference of the outer class. The property of the static class is that it does not allows us to access the non-static members of the outer class.
In Java, the static
keyword typically flags a method or field as existing not once per instance of a class, but once ever. A class exists once anyway so in effect, all classes are "static" in this way and all objects are instances of classes.
static
does have a meaning for inner classes, which is entirely different: Usually an inner class instance can access the members of an outer class instance that it's tied to, but if the inner class is static
, it does not have such a reference and can be instantiated without an instance of the outer class. Maybe you saw that someplace, then tried to use it on a top-level class, where it isn't meaningful.
Or maybe you saw it in other languages like C#, whose syntax is an awful lot like Java's.
(One time I couldn't figure out why an outer class instance wasn't being garbage-collected -- it was because I was keeping a reference to one of its inner class instances elsewhere, and the inner class was not static
and so had a reference to the outer class instance. So by default, I make inner classes static
now.)
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