what is an instance variable code example
Example 1: instance variable java
A variable declared inside the class is called instance variable. Value of
instance variable are instance specific.
public class InstanceVariableDemo
{
int c;
public void subtract()
{
int x = 100;
int y = 50;
c = x - y;
System.out.println("Subtraction: " + c);
}
public void multiply()
{
int m = 10;
int n = 5;
c = m * n;
System.out.println("Multiplication: " + c);
}
public static void main(String[] args)
{
InstanceVariableDemo obj = new InstanceVariableDemo();
obj.subtract();
obj.multiply();
}
}
Example 2: instance variables
Instance Belongs to the object
You can have multiple copies of instance variables
Example 3: what is class instance local variable
Class variables also known as static
variables are declared with the static
keyword in a class, but outside a method,
constructor or a block. There would
only be one copy of each class variable
per class, regardless of how many
objects are created from it.
Instance variables
are declared in a class, but outside
a method. When space is allocated for
an object in the heap, a slot for each
instance variable value is created.
Instance variables hold values that must
be referenced by more than one method,
constructor or block, or essential parts
of an object's state that must be present
throughout the class.
Local variables are declared in methods,
constructors, or blocks. Local variables
are created when the method, constructor
or block is entered and the variable will
be destroyed once it exits the method,
constructor, or block.