In Java, an instance field is a field (also known as a member variable) that belongs to an instance of a class, rather than to the class itself. An instance field is defined in a class and can be accessed using an instance of that class.
For example, consider the following class definition:
public class MyClass { // instance field private int x; // constructor public MyClass(int x) { this.x = x; } // instance method public void printX() { System.out.println(x); } }
In this example, the x
field is an instance field. It can be accessed using an instance of MyClass
:
MyClass obj = new MyClass(5); obj.printX(); // prints 5
Instance fields can have any accessibility level (e.g. public
, private
, protected
, etc.) and can be accessed or modified using instance methods or using the this
keyword.
For more information on instance fields in Java, you can refer to the Java documentation.