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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With