+ 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?
4 Respuestas
+ 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.
+ 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 ...
+ 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
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"