Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Instance methods and variables

Posted By: Dylan Bouchard     Category: Java     Views: 8458

This article explains about instance methods and variables in a class in java.

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.  
  
Share: 


Didn't find what you were looking for? Find more on Instance methods and variables Or get search suggestion and latest updates.

Dylan Bouchard
Dylan Bouchard author of Instance methods and variables is from Montreal, Canada.
 
View All Articles

Related Articles and Code:


 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!