Thursday, 26 December 2019

Why a non-static method can’t be referenced in static context?

Let me try to explain this with an example.

App.java
package com.sample.app;

public class App {

 public void sayHello() {
  System.out.println("Hello!!!!!");
 }

 public static void main(String args[]) {
  //sayHello();
 }
}

As you see above snippet, sayHello is an instance method. To call instance method you must create an object, but in case of static methods, they can be called without creating object.

Suppose if you try to call instance method directly within static context, A static method don’t know which particular object the non-static member (member can be field or method) belongs to. Since there is no existing object, non-static method doesn't belong to any object. Hence there is no way a non-static method can be referenced from static context.

Uncomment following statement in App.java.
//sayHello();

Try to compile App.java after uncommenting, you will get below error from java compiler.

Cannot make a static reference to the non-static method sayHello() from the type App.



You may like

No comments:

Post a Comment