How to use Objects as Parameter

  • 0
     The first thing that anyone needs to know is the difference between argument and parameters. Arguments are the variables that are passed to the functions and parameters are the variables that receive the value of the arguments. Java rich Object Oriented Features allow us to use Objects as the parameter.

     The only point that needs to be taken care of is that when objects are passed to a method, they are always passed via call be referance. So, any changes made to the object values in the method would be reflected in the passed object values too.


Fallowing program illustrates the method.
package ClassIllustration;

class ObjectsAsParameter
{
 int array[] = new int[10];
 
 int max(ObjectsAsParameter oap)
 {
  int i, max=-1;
  
  for(i=0;i<10;i++)
  {
   if(max<array[i])
   {
    max= array[i];
   }
  }
  return max;
 }
 
 public static void main(String args[])
 {
  ObjectsAsParameter oap = new ObjectsAsParameter();
  
  int i;
  for(i=0;i<10;i++)
  {
   oap.array[i]=i;
  }
  System.out.println("Maximum number is " + oap.max(oap));
 }
}
To compile the program :-
javac -d . ObjectsAsParameter.java
To run the program
java ClassIllustration.ObjectsAsParameter

No comments:

Post a Comment