I'm working with Java; I have worked with C++ before. I am thinking about static usage in Java. If I create static methods and variables in the class, Why can I access them through the object also?
Example:
class Test{
static int count=0;
int id;
static void updatec(){
count++
}
}
class TestMain
{
public static void main(String args[])
{
Test.count=1;
Test t = new Test();
t.count=5; // Valid WHY ?????
}
}
Why this is allowed? Java's site says we should not use obj.static method/variable.
Why it is allowed?
Static doesn't mean that the field is only for the class. It means it for the class and all its instances.
But you're right it's usually a bad idea to refer to a static field/method/class from a non-static context, it can confuse the developer.
Resources :
You shouldn't doesn't mean you can't.
Anyway, this is allowed in C++ also.
It's legal to access static fields through an instance, although you'll generally get a warning about it. The field is still static, however, so there's only one per class:
Your snippet is perfectly legit, either in Java or C++ equivalent.
It seems you're confusing access restriction (private, protected, public) and instance/class distinction for members (static keyword).
Since you have an instance of class Test (named t) in your static main method, you can use instance methods/members of class Test, that's conforming with the documentation you quoted.
If the count field was private or protected, you wouldn't be able to access it, but that would have nothing to do with static.
It really should not have been supported. This support leads to this dubious code in
org.apache.commons.cli
command-line parser.This leads to this:
It would be much better and cleaner and thread-safe, if there were a default
OptionBuilder
constructor and all static methods were instance methods. That's the model used byStringBuilder
/StringBuffer
static in this case means there's one shared instance per class, not per instance. So when you change t.count, you're changing the 'count' member for the whole class and ALL instances.
That is, these will print the same value:
There's nothing illegal about it, although it's usually not a great idea because it looks like instance data.