Reference Static Methods/Variables in Java from an Instance

后端 未结 5 1153
傲寒
傲寒 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:58

    public class MyClass {
        public static String myString;
    }
    
    
    public class AnotherClass {
       public void doSomething() {
           doAnotherThing();
       }
       public static doAnotherThing() {
           MyClass.myString = "something";
       }
    

    Here we are accessing static variable from non-static method (indirectly) by calling static method from non static method.

提交回复
热议问题