静态方法可以访问和修改 java 中的非静态字段吗?
Can a static method access and modify a non-static field in java?
这是代码,我试图在静态方法中使用非静态字段,但我不知道该怎么做。
包裹 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;
}
}
简单的答案是否定的。您不能在静态方法中访问非静态字段。
主题问题的简短回答是否。您无法从 Java 中的静态上下文访问非静态字段和方法。您只能做相反的事情:从对象实例获取静态信息。您需要向静态方法(作为参数)提供对象实例以对其进行操作。
顺便说一句,请重新格式化您的代码示例。它不可编译:)
这是工作概念
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;
}
}
这是代码,我试图在静态方法中使用非静态字段,但我不知道该怎么做。 包裹 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;
}
}
简单的答案是否定的。您不能在静态方法中访问非静态字段。
主题问题的简短回答是否。您无法从 Java 中的静态上下文访问非静态字段和方法。您只能做相反的事情:从对象实例获取静态信息。您需要向静态方法(作为参数)提供对象实例以对其进行操作。
顺便说一句,请重新格式化您的代码示例。它不可编译:)
这是工作概念
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;
}
}