0
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.:?:

2
Contributors
4
Replies
6
Views
7 Years
Discussion Span
Last Post by amalwit
0

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();
  }
}
0

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

0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.