27.7k views
0 votes
How can an instance variable be used in a class? Explain your answer. (java)

User Bento
by
5.5k points

1 Answer

3 votes

Answer:

Instantiate the object and access the variable using object reference.

Step-by-step explanation:

In order to use/access an instance variable in a class, the class needs to be instantiated.For example:

class Demo{

//Instance variable declaration

int testvar=0;

public static void main(String args[]){

//Class instantiation

Demo d = new Demo();

// The instance variable is accessed using the object reference

d.testvar = 1;

}

}

In case the instance variable in private then it can be accessed using its corresponding getter/setter methods.

User Bacar
by
5.5k points