Can static method access non-static instance variable?

后端 未结 5 2208
天命终不由人
天命终不由人 2020-12-16 19:31

So my understanding was that you can\'t use static method to access non-static variables, but I came across following code.

class Laptop {
  String memory =          


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-16 19:49

    Yes, a non-static method can access a static variable or call a static method in Java. There is no problem with that because of static members

    i.e. both static variable and static methods belongs to a class and can be called from anywhere, depending upon their access modifier.

    For example, if a static variable is private then it can only be accessed from the class itself, but you can access a public static variable from anywhere.

    Similarly, a private static method can be called from a non-static method of the same class but a public static method e.g. main() can be called from anywhere

提交回复
热议问题