Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Instance variable in java

 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.




This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

Instance variable in java

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×