A instance method is associated with and operates upon an object. Therefore, it is necessary to create an instance of that class in order to invoke such a method.
Syntax of instance method
retType funcName(paramList)
{
// Body of this method
}
Syntax to call instance method
objRef.funcName(args);
objRef is an object reference variable and funcName is the name of the method. args are an optional arguments.
stringclass provides several good examples of instance methods. For example,
int length()
String substring(int start)
Instance variable
An instance variable is associated with an object. It is necessary to create an instance of a class in order to read or write it.
Syntax of Instance variable
dataType varName1,...... varNameN;
Where varName1 is a name of the variable and required type is dataType.
Instance variables are initialized to default value during the creation of an object. Variables of type boolean are set to false. Numbers are set to zero. Any variable that acts as an object reference is set to null.
Example of instance method and instance variable
class Circle
{
// Instance Variables
double x;
double y;
double radius;
// Instance Method
void scale(double a)
{
radius *= a;
}
}
Here class circle defines instance variables and instance method.