1

I want my main class to print a message when I call it, for example:

Complex x = new Complex(1, 20);
System.out.println(x);

and with that, there will be a message.

I tried creating a function called "messages". For example I have:

public Complex add(Complex op){
        Complex x=new Complex(this.a, this.b);
        x.a+=op.a;
        x.b+=op.b;
        return x.messages("Random Message");
}

Although this does work, I want for it to be:

public Complex add(Complex op){
        Complex x=new Complex(this.a, this.b);
        x.a+=op.a;
        x.b+=op.b;
        return x;
}

without having to use a secondary function so back in the main class:

Complex y=new Complex(5, 8);
Complex z=new Complex(15,6);
System.out.println(y.add(z));

it will make a message appear. Thank you in advance!

  • 2
    You need to write the `toString()` method. Whenever java prints an object, toString is used to specify how it should be outputted. – Locke May 29 '19 at 17:11
  • It's possible that you [could use AOP to intercept the method call](https://stackoverflow.com/questions/22270363/how-to-capture-the-parameters-of-system-out-println-in-aspectjs-aspect-and-di/22295197), examine the class of the argument `arg.getClass().equals(Complex.class)` and then take whatever action. Not to be recommended, especially to a beginner, but anyway. – Michael May 29 '19 at 17:13
  • I would be grateful, if you could provide me an example – Georgios Glinias May 29 '19 at 17:13
  • If I am not missing something, you are looking for : System.out.println("Random Message" + y.add(z)); – AmitD May 29 '19 at 17:18
  • Thought of that as well but I want to use the class' variables as well. I tried the toString() method and it works like a charm. Thank you, Locke – Georgios Glinias May 29 '19 at 17:21

0 Answers0