Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accesing static variable from another class in java

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 this queue as public static and accessing it through getter, but without success Can somebody tell me what is the exact problem.

This is my code: Queue Declaration:

public static Queue<Request> q=new ConcurrentLinkedQueue<Request>();

public static void setQ(Queue<Request> q) {
        Connection.q = q;
    }

    public static Queue<Request> getQ() {
        return q;
    }

Accesing Queue:

Queue<Request> queue=new ConcurrentLinkedQueue<Request>(); 
queue=Connection.getQ();

Adding Value to Queue in thread of connection

q.add(r);
like image 708
Anup Avatar asked Apr 23 '12 11:04

Anup


People also ask

Can we access a static variable from one class to another?

In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.

Can static variables be accessed outside the class Java?

From outside the class, "static variables should be accessed by calling with class name." From the inside, the class qualification is inferred by the compiler.

How do you access a static method from a different class?

If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined. For instance methods, this is the object that the method will access. For static methods, the class name should be specified.

Can Java access static variables?

Accessibility of the Static Variables in Java. Static variables can be accessed by calling the class name of the class. There is no need to create an instance of the class for accessing the static variables because static variables are the class variables and are shared among all the class instances.


1 Answers

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.

like image 52
T.J. Crowder Avatar answered Oct 04 '22 01:10

T.J. Crowder