Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a Java class be declared as static?

Tags:

java

oop

class

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);     } } 
like image 532
gmhk Avatar asked Mar 04 '10 04:03

gmhk


People also ask

Why can't we declare a class as static in Java?

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.

Can Java class be static?

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.

What Cannot be declared as static in Java?

In Java, a static method cannot be abstract.

Can we declare class as a static?

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.


1 Answers

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.)

like image 76
easeout Avatar answered Sep 21 '22 12:09

easeout