'Can a static method access and modify a non-static field in java? [duplicate]

Here is the code, I'm trying to use a non-static field in a static-method, but I don't know how to do it. package hombre.numbro;

public class EmployeeLinkedList {
    private EmployeeNode head;
    public void addToFront(Employee employee) {
    EmployeeNode node = new EmployeeNode(employee);
    node.setNext(head);
    head = node;
}
public void printList() {
    EmployeeNode current = head;
    System.out.print("HEAD -> ");
    while (current != null) {
        System.out.print(current);
        System.out.println();
        System.out.print(" -> ");
        current = current.getNext();
    }
    System.out.print("null");
}
public static Employee removeFromFront(Employee employee) {
    EmployeeNode removedNode = list.head;

}

}



Solution 1:[1]

The simple answer is no. You can not access a non-static field in a static method.

Solution 2:[2]

The short answer to the topic question is no. You can't access non-static fields and methods from a static context in Java. You can do only oposite: reach statics from object instance. You need to provide object instance to static method (as argument) to operate on it.

BTW reformat your code example, please. It's not compilable :)


Here is working concept

public class Example {
   public static String staticField;
   public String nonStaticField;

   public static String getNonStaticFieldFromStaticContext(Example object) {
      return object.nonStaticField;
   }

   public String getNonStaticField() {
      return this.nonStaticField;
   }

   public static String getStaticField() {
      return Example.staticField;
   }

   public String getStaticFieldFromNonStaticContext() {
      return Example.staticField;
   }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2