Instance Variables
Instance Variables are variables defined inside a class, but not inside the parameter list of a method
or inside the method itself (i.e. not a local variable or temporary variable).
Examples:
// The following MyPoint class holds the coordinates
// for a point on a 2D plane.
// The class has 2 instance variables that are defined
// The instance variables always exist for each object
// that exists of the type
public class MyPoint {
// instance variables x and y are defined below
// storage is always available
// for the life of an object of this type
public int x; // instance variable x
public int y; // instance variable y
// constructor MyPoint with 2 parameters
// this.x refers to the instance variable x
// this.y refers to the instance variable x
// x and y refer to the temporary parameter variables x and y
// which only exist when the constructor is called (invoked)
public MyPoint(int x, int y)
{
this.x = x;
this.y = y;
}
// method getX() will return an int
// which is the value of the instance variable x
// we do not need to say this.x because there is no local variable x
// this is called a getter method since it returns the value of an instance variable
public int getX()
{
return x; // or we could say return this.x;
}
// method setX(int x) does not return a value
// it receives a value and then assigns that value to the instance variable x
// this is called a setter method since it sets the value of an instance variable
public void setX(int x)
{
this.x = x;
}
// other methods not shown
}