Java Static confusion

2019-04-11 21:11发布

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?

标签: java static
7条回答
Fickle 薄情
2楼-- · 2019-04-11 21:58

There is no good reason why this is allowed. It's confusing and it serves no purpose. Good tools will warn you about this (or maybe even give you the option to fail compilations over it). But it is part of the language and so it will never be taken out because that would break existing code.

查看更多
登录 后发表回答