OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 13 : Class Objects as Parameters in Methods

 

Unit - 2

Topic - 13 : Class Objects as Parameters in Methods

In Java, you can pass entire objects as parameters to methods.
This allows you to compare objects, update their values, or perform operations involving multiple instances of a class.


Example: Passing Objects to Methods

class Test { int a, b; // Constructor Test(int i, int j) { a = i; b = j; } // Compare two Test objects 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)); } }

Output:

ob1 == ob2: true ob1 == ob3: false

Explanation:

  • The equals() method takes another Test object as a parameter.

  • Inside the method:

    • It compares the instance variables of the invoking object with those of the passed object.

    • If both objects have the same values for a and b, it returns true.

    • Otherwise, it returns false.

  • The type of parameter o is Test, which means only objects of class Test can be passed to this method.


Key Points:

  • Objects in Java are passed by reference (more precisely, object references are passed by value).

  • Passing objects to methods allows direct access to their data members.

  • You can create methods to compare, copy, or merge objects easily.

Comments

Popular posts from this blog

Career Guide - B.Tech Students

Artificial Intelligence - UNIT - 1 Topic - 1 : Introduction to AI (Artificial Intelligence)

Financial Aid for Students: Scholarships from Government, NGOs & Companies