Solve Cannot make a static reference to the non-static method Error

Here you will learn to solve error “cannot make a static reference to the non-static method” or “non static method cannot be referenced from a static context”.

Lets take one example where this error occurs.

When you will compile below code then you will get an error.

public class DemoClass {
	void print() {
		System.out.println("Hello World");
	}
	
	public static void main(String args[]) {
		print();
	}
}

solve error cannot make a static reference to the non-static method or non static method cannot be referenced from a static context

Why this Error Occurs?

This error occurs when we try to access a non static method or member directly inside a static method.

In above code print() is a non static method and we are calling it inside main() method which is static.

How to Solve this Error?

Below I have mentioned some possible solutions for this error.

1. Making Method static

We can simply convert non static method to static. Then we can call it directly inside static method. Take below example.

public class DemoClass {
	static void print() {
		System.out.println("Hello World");
	}
	
	public static void main(String args[]) {
		print();
	}
}

Now the above code will not show error and work properly.

2. Calling Method Using Instance

Another solution is to create an instance or object of the class and then call the non static method inside static method. Take below example.

public class DemoClass {
	void print() {
		System.out.println("Hello World");
	}
	
	public static void main(String args[]) {
		DemoClass object = new DemoClass();
		object.print();
	}
}

See in above program I have first created object of DemoClass and then called print() method inside main() method.

Comment below if still you are unable to solve errorĀ “cannot make a static reference to the non-static method” or “non static method cannot be referenced from a static context”.

Leave a Comment

Your email address will not be published. Required fields are marked *