Instance Method With Parameter
Instance method with parameter takes the argument when it is called in the main method. Now let’s see Examples for better understanding.
Syntax:
modifier return_type method_name( parameter list) { method body ; }
- Parameter List: The list of parameters separated by a comma. These are optional; the method may contain zero parameters.
Example:
public void disp(int a, int b) { int x=a ; int y=b; int z = x+y; System.out.println(z); }
Java
// Java program to see how can we call // an instance method with parameter import java.io.*; class GFG { // static method public static void main (String[] args) { // creating object GFG obj = new GFG(); // calling instance method by passing value obj.add( 2 , 3 ); System.out.println( "GFG!" ); } // Instance method with parameter void add( int a, int b) { // local variables int x= a; int y= b; int z= x + y; System.out.println( "Sum : " + z); } } |
Sum : 5 GFG!
Instance Methods in Java
Instance Methods are the group of codes that performs a particular task. Sometimes the program grows in size, and we want to separate the logic of the main method from other methods. A method is a function written inside the class. Since java is an object-oriented programming language, we need to write a method inside some classes.
The important points regarding instance variables are:
- Instance methods can access instance variables and instance methods directly and undeviatingly.
- Instance methods can access static variables and static methods directly.