TutorialsISCClass 12Computer Science

Passing Objects to Methods in Java for ISC Class 12 (Object as Parameter and Return Type)

ISC Class 12 Computer Science notes on object passing: passing an object as a parameter, returning an object from a method, using this to access the current object, and a fully solved board-style Distance class program.

11 min read
Passing Objects to Methods in Java for ISC Class 12 (Object as Parameter and Return Type)

Many ISC Section B questions follow one pattern: "design a class… with a method that accepts an object of the same class and returns an object". Examples are adding two times, merging two arrays, or comparing two dates. Once you understand how objects are passed, these questions become routine.

How Java passes objects

When you pass an object to a method, Java passes a reference to it. The method works on the same object, so changes it makes to the object's data members are visible to the caller.

class Box {
    int size;
}

static void grow(Box b) {
    b.size = b.size * 2;      // changes the caller's object
}

Box x = new Box();
x.size = 5;
grow(x);
System.out.println(x.size);   // 10

Compare this with primitives (int, double and so on), where the method gets a copy and the original never changes.

The current object and the parameter object

Inside a method such as obj1.add(obj2):

  • the data members written on their own (or as this.feet) belong to obj1, the current object;
  • obj2.feet belongs to the parameter object.

Returning an object

A method can create a new object, fill it in and return it:

Distance add(Distance d) {
    Distance t = new Distance();
    // ... fill in t ...
    return t;
}

Solved board-style program: class Distance

Question: Design a class Distance with these members:

  • Data members: int feet, int inches
  • Distance(): default constructor that sets both to 0
  • Distance(int f, int i): parameterised constructor
  • Distance add(Distance d): returns a new object holding the sum of the current distance and d, with inches adjusted so they are less than 12
  • boolean isLonger(Distance d): returns true if the current distance is longer than d
  • void show(): prints the distance as feet' inches"

Write a main() method to add 5' 8" and 3' 7".

class Distance {
    int feet, inches;

    Distance() {
        feet = 0;
        inches = 0;
    }

    Distance(int f, int i) {
        feet = f;
        inches = i;
    }

    Distance add(Distance d) {
        Distance t = new Distance();
        int totalInches = this.inches + d.inches;
        t.inches = totalInches % 12;
        t.feet = this.feet + d.feet + totalInches / 12;
        return t;
    }

    boolean isLonger(Distance d) {
        return (feet * 12 + inches) > (d.feet * 12 + d.inches);
    }

    void show() {
        System.out.println(feet + "' " + inches + "\"");
    }

    public static void main(String args[]) {
        Distance d1 = new Distance(5, 8);
        Distance d2 = new Distance(3, 7);
        Distance d3 = d1.add(d2);
        d3.show();                              // 9' 3"
        System.out.println(d1.isLonger(d2));    // true
    }
}

How the sum works: 8 + 7 = 15 inches, which is 1 foot and 3 inches. Feet = 5 + 3 + 1 = 9, so the result is 9' 3".

A second common pattern: merging two arrays into one object

ISC questions often wrap an array in a class and ask for a method that merges two objects:

class Collection {
    int arr[];
    int len;

    Collection(int n) {
        len = n;
        arr = new int[n];
    }

    Collection merge(Collection c) {
        Collection r = new Collection(this.len + c.len);
        for (int i = 0; i < this.len; i++)
            r.arr[i] = this.arr[i];
        for (int i = 0; i < c.len; i++)
            r.arr[this.len + i] = c.arr[i];
        return r;
    }
}

Exam tips

  1. Create the result object with new inside the method. Don't modify this unless the question says the current object should change.
  2. Use this.member and param.member consistently, so the examiner can see which object you mean.
  3. Always write the return type as the class name (for example Distance add(Distance d)) and finish with return.
  4. In main(), show the call in the form obj3 = obj1.method(obj2);. Examiners look for it.

Practice questions

  1. What is printed if grow(x) above instead sets b = new Box(); b.size = 50;?
  2. Write a method Time addTime(Time t) that adds two times given in hours and minutes.
  3. Why must a method that returns an object create it with new?

Answers:

  1. 5. The method points b at a new object, so the caller's object is untouched.
  2. Add the minutes, carry total / 60 into the hours, and keep total % 60 as the minutes. The structure is the same as add() above.
  3. Otherwise there is no object to return. Returning this would hand back, and possibly change, the caller's own object instead of a separate result.

Revise Inheritance, Abstract Classes and Interfaces and Stack, Queue and Linked List to complete the ISC Class 12 Java syllabus.