Accesing static variable from another class in java

前端 未结 2 1616
遥遥无期
遥遥无期 2020-12-19 10:43

I had a queue implemented as linked list in my multithreaded server. I want to access this queue from another class. Both classes are in the same package. I tried making thi

2条回答
  •  孤城傲影
    2020-12-19 11:09

    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.

提交回复
热议问题