We can call a method without creating object of the class by declaring it as static, than what is the need of creating object? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

We can call a method without creating object of the class by declaring it as static, than what is the need of creating object?

Why not every method is declared as static in java?

11th Feb 2020, 3:06 PM
Piyush Srivastava
Piyush Srivastava - avatar
4 Answers
+ 3
I will try my best to answer this with the little knowledge I have. If a method is declared static, then you can access only static data members of the class and non-static data members are not accessible. But if a method is non-static then you can access both static and non-static data members of the class. Also static keyword means that it is a class level member and only a single copy of it is created which would be shared by all the objects of the class. Another problem with them is that they keep on updating themselves with the last value assigned. So then all the objects would end up having the same state if we use static members alone. Hope you have got some idea.
11th Feb 2020, 3:47 PM
Avinesh
Avinesh - avatar
+ 1
because if you have class student with instances then you can create objects s1, s2, s3 each with specific values, eg s1.name = "John Doe"; s2.name ...
11th Feb 2020, 3:33 PM
zemiak
+ 1
To complement zemiak I wrote a small code where you can see that static methods are not always helpful. https://code.sololearn.com/c49gsn816ZyO/?ref=app
12th Feb 2020, 1:02 AM
Denise Roßberg
Denise Roßberg - avatar
0
if you call static member of object a = obj.staticVariable; compiler display warning (if warnings are on) "warning: [static] static variable should be qualified by type name, A, instead of by an expression"
11th Feb 2020, 4:09 PM
zemiak