1

In java, An outer class may be public, final, default or abstract. Why not Static like

public static class MyClass{}

3
  • 2
    What semantics would you expect a static class to have, as opposed to static members of a class? Commented Sep 11, 2013 at 9:56
  • Because it's redundant and expresses nothing, and raises the false expectation that omitting the word 'static' changes the meaning when it doesn't. Commented Sep 11, 2013 at 10:28
  • Please read the answer to your question, Why can't a Java class be declared as static? on stackoverflow.com/a/40015089/2078093 Commented Oct 13, 2016 at 7:46

1 Answer 1

4

An outer class is already implicitly static.

Non-static nested class (= inner class) means thats the inner class implicitly has a reference to its parent class.

That's why, for nested class, you can distinguish between static and non-static. This does not make sense for outer classes.

Here is an example to understand the difference between static/non-static nested class. You should understand why it does not make sense in an outer class.

public class MyClass {

  private String anAttributeOfMyClass;

  private /*static*/ class MyInnerClass {

    public void foo() {
      /*
       * Here, I can access the attribute of the parent class
       * because I implicitly have a reference to it.
       * Try to make the nested class static an see the difference.
       */
      anAttributeOfMyClass.trim();
    }
  }

}
Sign up to request clarification or add additional context in comments.

8 Comments

can you please elaborate? this is new for me
As you describe the notion it is anyway irrelevant to static class in other languages like C# which cannot be instantiated.
an interface method is implicitly public and abstract, but even if we declare them as public and abstract, it is valid. Then why is it incorrect to declare an outer class as static if it is implicitly static? I am not sure I'm following this answer.
@Prasad True. And if you explicitly declare interface methods as public, Sonar will complain about it. But in java 8, you might be able to write complete methods in interfaces and I guess it will be useful to be able to choose the visibility.
@Prasad Same remark for abstract. In Java 8 interfaces, you will be able to choose between abstract and default. See blog.hartveld.com/2013/03/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.