user1769501
user1769501

Reputation:

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 ?

Upvotes: 10

Views: 4762

Answers (3)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

- 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...

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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.

Upvotes: 8

kosa
kosa

Reputation: 66637

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.

Upvotes: 6

Related Questions