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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>