Accesing static variable from another class in java

可紊 提交于 2019-12-06 01:42:50

You can access a public static member of another class directly, using the notation ClassName.memberName:

public class Foo {
    public static String bar = "hi there";
}

public class Thing {
    public static void main(String[] args) {
        System.out.println(Foo.bar); // "hi there"
   }
}

public static data members are usually not a great idea (unless they've final), but if you need one, that's how you do it.

You should be able to access if directly, or using static getter methods...

If this is your Queue class...

public class Queue {
    public static LinkedList myList = new LinkedList();

    public static ListedList getMyList(){
        return myList;
    }
}

Then you could access your list be either calling Queue.myList or Queue.getMyList() - both will do the same thing. The benefit of using a getter method would be that you can control access to the list, such as by making the method synchronized, preventing calls to the list being out of order.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!