Reference Static Methods/Variables in Java from an Instance

后端 未结 5 1150
傲寒
傲寒 2020-12-11 20:17

Can anyone explain to me why java allows you to access static methods and members from an instance? A bad example, if I have a class called RedShape and it has a static meth

5条回答
  •  自闭症患者
    2020-12-11 20:41

    I don't see anything wrong with calling a static method from an instance. What's wrong with that? In particular, quite often there are methods which are useful within the logic of a class, but which don't actually need to manipulate the instance itself.

    I do object to calling a static method via an instance reference. Classic example:

    Thread thread = new Thread(...);
    thread.sleep(5000); // Doesn't do what it looks like
    

    This comes with a compiler warning in some IDEs - certainly in Eclipse, assuming you turn it on. (Java / Compiler / Errors and Warnings / Code Style / Non-static access to static member.) Personally I consider that a mistake in the design of Java. (It's one of the mistakes that C# managed to avoid copying.)

提交回复
热议问题