So far, we have only been using simple types as parameters to methods. However, it is both correct and common to pass objects to methods. For example, consider the following short program:

// Objects may be passed to methods.

class Test {

int a, b ;

Test ( int i, int j )   {

a = i ;

b = j ;

}

// return true if o is equal to the invoking object

Boolean equals (Test o)  {

if (o.a == a && o.b == b )   return true ;

else return false ;

}

}

class  PassOb  {

public static void main( String args[] )  {

Test ob1 = new Test (100, 22)  ;

Test ob2 = new Test (100, 22) ;

Test ob3 = new Test (-1, -1) ;

System.out. println(“ob1 == ob2 :  ” + ob1. equals(ob2 ) )  ;

System.out. println(“ob1 == ob3 :  ” + ob1. equals(ob3 ) )  ;

}  }

This program generates the following output:

ob1 == ob2 : true

ob1 == ob3 : false

Description –

As you can see, the equals( ) method inside Test compares two objects for equality and returns the result. That is, it compares the invoking object with the one that it is passed. If they contain the same values, then the method returns true. Otherwise, it returns false.

Notice that the parameter o in equals( ) specifies Test as its type. Although Test is a class type created by the program, it is used in just the same way as Java’s built- in types

Recommended Post   Overview Of Java

LEAVE A REPLY

Please enter your comment!
Please enter your name here