Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of Static methods in java

Tags:

java

static

i am confused about the usage of static methods in java , for example it makes sense if main method is static , but while coding we have got objects for example

 JFrame frame= new JFrame(); 
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// here why not frame.EXIT_ON_CLOSE

and same way when we use

 GridBagConstraints c= new GridBagConstraints();// we have an object but still
 c.anchor = GridBagConstraints.PAGE_END; 

so can anyone please explain me the is there any special reasons for it ?

like image 556
Sikander Nawaz Avatar asked Dec 02 '12 13:12

Sikander Nawaz


1 Answers

Static methods and fields belong to all objects in a class, as opposed to non-static ones, which belong to a particular instance of a class. In your example, no matter how many JFrame frame objects you create, accessing frame.EXIT_ON_CLOSE would produce the same exact result. To state this fact explicitly, static members (also known as "class members") are used.

Same logic applies to static methods: if a method does not access instance variables, its result becomes independent of the state of your object. The main(String[] args) method is one such example. Other common examples include various factory methods, parsing methods for primitives, and so on. These methods do not operate on an instance, so they are declared static.

like image 187
Sergey Kalinichenko Avatar answered Nov 15 '22 18:11

Sergey Kalinichenko