Home > Mobile >  Can a Java class have a method that works on multiple of its objects?
Can a Java class have a method that works on multiple of its objects?

Time:07-04

I have a simple task to code an immutable class Size with a single int field s. One of the class operations is "plus" that "adds two Size objects with the obvious result". The way I am reading it, I am supposed to use the method of an object of class Size to add itself to another object of class Size. I find it strange that an object's method would be to take itself and another instance of the same class as parameters. Is this normal? Or am I reading the question incorrectly?

CodePudding user response:

Yes this is normal and not too uncommon behavior. Look at the BigInteger class as an example of just this. Its add method does exactly what you are trying to do -- it returns a new immutable BigInteger instance that is the sum of the two values, the current value plus the parameter's value.

CodePudding user response:

This statement:

immutable class Size with a single int field "s"

... looks like this in code:

class Size {
    private final int s;

    public Size(int s) {
        this.s = s;
    }
}

This statement:

One of the class operations is "plus" that "adds two Size objects with the obvious result"

... is describing:

  • first Size with some value, say 9
  • second Size with some other value, say 17
  • some kind of add() function that would take those two Size objects and return a new Size object with the result of adding both Size objects above; namely, int value 26 (which came from 9 17)

Below is code that:

  • Starts with the same Size class as above
  • Adds a new getS() method to return the internal "s" number – we didn't need a getter until now, but we'll use it to add things
  • Adds a new add() method which:
    • Takes a required parameter of a second Size object, called "otherSize"
    • Uses the getS() method on "this" (meaning, whatever the first Size object you started with; in the example below, this refers to the Size containing "9") and getS() on "otherSize"
    • Constructs and returns a new Size object using the new value
class Size {
    private final int s;

    public Size(int s) {
        this.s = s;
    }

    public int getS() {
        return s;
    }

    public Size add(Size otherSize) {
        return new Size(this.getS()   otherSize.getS());
    }
}

Finally, here's code to construct a few Size objects, add them, print the result; I also included the output from running it. I chose variable names that should help explain what's going on.

Size nine = new Size(9);
Size seventeen = new Size(17);
Size twentySix = nine.add(seventeen);
System.out.println(twentySix.getS());

26
  • Related