简体   繁体   中英

Purpose of Static methods in java

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 ?

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.

JFrame.EXIT_ON_CLOSE is not a method. It is static field. See this doc .

If you don't want some functionality associated with class not object, then you can use static method.

- JFrame.EXIT_ON_CLOSE is a static variable (field) not method in JFrame Class.

- static methods are class methods, for example in Math class there is No instance variables, and its constructor is private. So static worked perfectly there...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM