Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a static method considered a method?

People also ask

Why this method is called static method?

Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.

What is a static method also known as?

A static method belongs to the class itself so a static method is also called class method. And since a static method doesn't belong to any instances of the class, it cannot access non-static methods or non-static variables of the class.

When should a method be defined as static?

You should consider making a method static in Java : 1) If a method doesn't modify the state of the object, or not using any instance variables. 2) You want to call the method without creating an instance of that class.


This quote from 8.4.3.2 may help:

A method that is declared static is called a class method.

A method that is not declared static is called an instance method [...].

  • Class methods: associated with a class.
  • Instance methods: associated with an instance.

Java just wants you to "think object-oriented". Also, static methods have access to a surrounding scope which may include state. In a way, the class is like an object itself.


The simple answer is that when Java decided to call everything a "method", they didn't care about the distinction between a function and a method in theoretical computer science.


Static methods are not exactly functions, the difference is subtle, but important.

A static method using only given input parameters is essentially a function.

But static methods may access static variables and other static functions (also using static variables) so static methods may have a state which is fundamentally different to a function which are by definition stateless. (ADDENDUM: While programmers are often not so strict with using "function" as definition, a strict function in computer science can access only input parameters). So defining this case of accessing static fields it is not valid to say that static methods are always functions.

Another difference which justifies the usage of "static method" is that you can define in C derivates global functions and global variables which can be accessed everywhere. If you cannot access the class which contain static methods, the methods are inaccessible, too. So "static methods" are limited in their scope by design in contrast to global functions.


In Java, a user-defined class is actually an instance of a subclass of java.lang.Class.

In this sense, static methods are attached to an instance of a conceptual class: they are attached to an instance of a subclass of java.lang.Class.

With this in mind, the term "class method" (an alternate name for Java's static methods) begins to make sense. And the term "class method" can be found in many places: Objective C, Smalltalk, and the JLS -- to name just a few.