Why does static have different meanings depending on the context? [duplicate]

Your examples are all correct, however, they all share a common feature. The word static means that an enclosing instance is not necessary.

  • Only a static inner class can exist without an enclosing instance. For example, if you have a class Foo and a non-static inner class Bar then you cannot create an instance of Bar outside an instance of Foo.

  • A static method means you do not need an instance of the class to call the method. You can call String.format without an actual String instance for example.

  • A static field will exist even without an instance of the class. If your Foo class has a counter field that is static you can access it without ever instantiating an instance of the Foo class.

Consider, as a clarifying point, that an interface can have static classes, static fields, and static methods. However, it cannot have the non-static version of any of those things (ignoring default methods which are sort of ad-hoc’d into the concept). This is because you can never create an instance of an interface so there could never be an enclosing instance.

You can also declare inner interfaces, annotations, and enums to be static although the keyword in that case is entirely redundant (e.g. similar to declaring an interface method abstract). Interfaces, annotations, and enums have no relationship to an enclosing class to begin with so static can’t really take that away.

One last byzantine point. If you do a static import (import static pack.age.Foo.*) you will be able to make unqualified references to any static items in a class (including interfaces, annotations, and enums regardless of whether or not they are redundantly marked static).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)