class A{
   void method(){
     System.out.println("Hello world");
   }
}
class B{
   void myMethod(){
     A.method();
   }   
}

Can anyone tell me why I am getting this error.( non-static method method() cannot be referenced from a static context).Reffering context is not static.:?:

Recommended Answers

All 4 Replies

A.method() is a static reference - A is a class not an instance. method() is an instance method - hence the error.
Contrast that with the following valid code

class B{
  void myMethod(){
    A a = new A();
    a.method();
  }
}

Your code is compiling.But myMethod() is not static so A.method() is not in a static context.

A. is a static context. Whatever follows that has to be static. It's not about then enclosing method, it's just the way you use the class name rather than an instance in that statement.

Thank you.I think my problem is solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.