Why Are You Not Able to Declare a Class as Static in Java

Why are you not able to declare a class as static in Java?

Only nested classes can be static. By doing so you can use the nested class without having an instance of the outer class.

class OuterClass {
public static class StaticNestedClass {
}

public class InnerClass {
}

public InnerClass getAnInnerClass() {
return new InnerClass();
}

//This method doesn't work
public static InnerClass getAnInnerClassStatically() {
return new InnerClass();
}
}

class OtherClass {
//Use of a static nested class:
private OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();

//Doesn't work
private OuterClass.InnerClass innerClass = new OuterClass.InnerClass();

//Use of an inner class:
private OuterClass outerclass= new OuterClass();
private OuterClass.InnerClass innerClass2 = outerclass.getAnInnerClass();
private OuterClass.InnerClass innerClass3 = outerclass.new InnerClass();
}

Sources :

  • Oracle tutorial on nested classes

On the same topic :

  • Java: Static vs non static inner class
  • Java inner class and static nested class

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

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

Why can't a top level class be static in Java?

All top-level classes are, by definition, static.

What the static boils down to is that an instance of the class can stand on its own. Or, the other way around: a non-static inner class (= instance inner class) cannot exist without an instance of the outer class. Since a top-level class does not have an outer class, it can't be anything but static.

Because all top-level classes are static, having the static keyword in a top-level class definition is pointless.

Some code to play around with:

public class Foo {

public class Bar {
// Non-static innner class
}

public static class Baz {
// Static inner class
}
}

public class Example {
public static void main(String[] args) {
new Foo(); // this is ok
new Foo.Baz(); // this is ok
new Foo.Bar(); // does not compile!

Foo f = new Foo();
Foo.Bar bar = f.new Bar(); //this works, but don't do this
}
}

I put the "but don't do this" in there because it's really ugly code design. Instance inner classes should not be visible outside the outer class. They should only be used from within the outer class.

Why is class declared as static in Java?

Firstly you cannot make top-level-class static. you can only make a nested class static. By making an nested class static you basically are saying that you don't need an instance of the nested class to use it from your outer class/top-level-class.

Example:

class Outer {

static class nestedStaticClass {

//its member variables and methods (don't nessarily need to be static)
//but cannot access members of the enclosing class
}

public void OuterMethod(){
//can access members of nestedStaticClass w/o an instance
}
}

Also to add, it is illegal to declare static fields inside an inner class unless they are constants (in other words, static final). As a static nested class isn't an inner class you can declare static members here.

Can class be nested in nested class?

In a word, yes. Look at the below Test, both nested inner classes and nested static class can have nested classes in 'em. But remember you can only declare a static class inside a top-level class, it is illegal to declare it inside an inner class.

public class Test {
public class Inner1 {
public class Inner2 {
public class Inner3 {

}
}
}
public static class nested1 {
public static class nested2 {
public static class nested3 {

}
}
}
}

Why there is no static class in Java

It is not a restriction, you do not need static class to define a utility class, you only need static methods. For example the class Math in java is full of static methods, but the class itself is not static.

You might only need static class when you define an inner class that you want to use without creating an instance of the enclosing class, which is allowed in Java.

You can define your utility class as follows:

class Util {
public static void method(){
// your utility method
}
}

Static Classes In Java

Java has static nested classes but it sounds like you're looking for a top-level static class. Java has no way of making a top-level class static but you can simulate a static class like this:

  • Declare your class final - Prevents extension of the class since extending a static class makes no sense
  • Make the constructor private - Prevents instantiation by client code as it makes no sense to instantiate a static class
  • Make all the members and functions of the class static - Since the class cannot be instantiated no instance methods can be called or instance fields accessed
  • Note that the compiler will not prevent you from declaring an instance (non-static) member. The issue will only show up if you attempt to call the instance member

Simple example per suggestions from above:

public class TestMyStaticClass {
public static void main(String []args){
MyStaticClass.setMyStaticMember(5);
System.out.println("Static value: " + MyStaticClass.getMyStaticMember());
System.out.println("Value squared: " + MyStaticClass.squareMyStaticMember());
// MyStaticClass x = new MyStaticClass(); // results in compile time error
}
}

// A top-level Java class mimicking static class behavior
public final class MyStaticClass {
private MyStaticClass () { // private constructor
myStaticMember = 1;
}
private static int myStaticMember;
public static void setMyStaticMember(int val) {
myStaticMember = val;
}
public static int getMyStaticMember() {
return myStaticMember;
}
public static int squareMyStaticMember() {
return myStaticMember * myStaticMember;
}
}

What good are static classes? A good use of a static class is in defining one-off, utility and/or library classes where instantiation would not make sense. A great example is the Math class that contains some mathematical constants such as PI and E and simply provides mathematical calculations. Requiring instantiation in such a case would be unnecessary and confusing. See the Math class and source code. Notice that it is final and all of its members are static. If Java allowed top-level classes to be declared static then the Math class would indeed be static.

Top level classes cannot be static in java but inner classes can be why ?

static classes means there is no reference to an instance of an outer class.

Top level classes cannot have a reference to an outer class, so in a way they are all static classes.

The reason you can't make them static, is there is no other option and the syntax for top level classes was determined before there was a option for nested classes.

Why local classes in static methods are not static

"Local classes are non-static because they have access to instance members of the enclosing block." - if the block is static so it have acess inside the block, if it is not so it have access to the class.

A static variable is not from any instance, it is static. You can access any static member in any static context (according to visibility of course).

Static is a virus keyword, if you remove it from the name inside the non-static AnotherClass you will see that you can't use it at printMembers(), removing it you will not be able to call from class name and will need a instance, cause in this case it will be a instance member and not static.

A static local class would have some uses when creating a type without context, in the way it is done, you have access to variables in the context, so the final variables in the static method (context) is acessible in the local class.

In a non static block, the local class will always be of instance and have access to the methods of the outer class.

Why can't I declare a parameterized static class variable?

Edit: Now I see the problem better.

I think that firstly you would have to declare the type as a class parameter:

class MyClass<Z> {

to get visibility, but now the reason you can't use it like that is because the static member should be shared among all the instances of the class. But since you could create instances with different type parameters, the static member depending on a particular type would not make sense.



Related Topics



Leave a reply



Submit