In Java, an instance variable is a variable that is declared in a class, outside of any method or constructor, and that is associated with a specific instance of the class.
Each object of the class will have its own copy of the instance variable, which can have different values for different objects.
Here's an example of a class called Person with an instance variable called name:
In this example, the name variable is declared as a private instance variable, and is therefore only accessible through the class's public getName and setName methods.
The class Person has a constructor that accepts a name and assigns it to the instance variable name.
When an object of the Person class is created, it gets its own copy of the name variable.
Person john = new Person("John");
Person jane = new Person("Jane");
In this example, the john object has its own copy of the name variable, which is set to "John", while the jane object has its own copy of the name variable, which is set to "Jane".
Instance variables are also known as non-static fields. They are created each time when an object of the class is created, and if they are not initialized explicitly they get a default value (null for objects, 0 for numeric types, etc). They can also be accessed through object reference.
Instance variables are usually used to store the state of an object, and are typically marked as private, to enforce encapsulation and to prevent other classes from directly accessing the data.
No comments