The purpose of static methods in Java
I'm confused about the use of static methods in Java. For example, if the main method is static, it makes sense, but we already have objects when coding
JFrame frame= new JFrame(); frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);// here why not frame.EXIT_ON_CLOSE
The same way when we use
GridBagConstraints c= new GridBagConstraints();// we have an object but still c.anchor = GridBagConstraints.PAGE_END;
Anyone can explain. Is there any special reason?
Solution
Static methods and fields belong to all objects in the class, rather than static methods and properties belong to specific instances of the class In your example, no matter how many JFrame frame objects you create, access frame EXIT_ ON_ Close will produce the same exact results To clarify this fact, use static members (also known as "class members")
The same logic applies to static methods: if a method does not access instance variables, the result will be independent of the state of your object The main (string [] args) method is an example Other common examples include various factory methods, primitive parsing methods, etc These methods do not operate on instances, so they are declared static