Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non static field cannot be referenced from a static context- Main method [duplicate]

I have 2 classes in my Spring-Boot application:

-Tasks

-Runner

The runner class contains my main method where I try to call a method from my Tasks class:

Runner:

@Component
public class Runner {

    Tasks tasks;    

    @Autowired
    public void setTasks(Tasks tasks){
        this.tasks=tasks;
    }

    public static void main(String[] args){

    //error being caused by below line
    tasks.createTaskList();

    }

Tasks Class:

@Service
public class Tasks {

    public void createTaskList() {

    //my code
    }


    //other methods 


}

In my Runner, when I try to call the createTaskList() method in the Tasks class I get the following error:

Non static field 'tasks' cannot be referenced from a static context

How can I solve this?

like image 286
java123999 Avatar asked Apr 25 '16 13:04

java123999


People also ask

Can you access a non-static variable in the static context?

Of course, they can but the opposite is not true i.e. you cannot access a non-static member from a static context i.e. static method. The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs.

How do you create a static reference to a non-static field?

i.e. referring a variable using static reference implies to referring using the class name. But, to access instance variables it is a must to create an object, these are not available in the memory, before instantiation. Therefore, you cannot make static reference to non-static fields(variables) in Java.

How do you assign a non-static variable to a static variable?

You cannot assign the result of a non-static method to a static variable. Instead, you would need to convert the getIPZip method to be a static method of your MyProps class, then you could assign its result to yor IPZip variable like this. public static String IPZip = MyProps. getIPZip("IPZip");

Why can't we call non-static method from static method?

You cannot call non-static methods or access non-static fields from main or any other static method, because non-static members belong to a class instance, not to the entire class.


1 Answers

The main method is static meaning that it belongs to the class and not some object. As such, it a static context cannot reference an instance variable because it wouldn't know what instance of Runner it would use if there even was one.

In short, the solution is to make your Tasks object static in the Runner class.

like image 154
Zircon Avatar answered Sep 30 '22 12:09

Zircon