Ask coding questions

← Back to all posts
Methods with same signature in Java (different return type)
BatuhanBatuhan (1)

Hello,

I have a Java assignment. I am supposed to make a class with two "Multiply" methods one returns the result and the other returns void and modifies the object that invokes it.

How is this possible in Java? Just giving me some keywords for where to look would be very helpful. Inheritance? Polymorphism? Interfaces? Abstract classes?

Cheers

Commentshotnewtop
eankeen (658)

Hi!
So you won't really need to know about inheritance, polymorphism, etc. to do this. I found a page on the official documentation, but there are great sources elsewhere. Yeah, and keywords such as instantiate, class, overloading and method declaration might help when searching.

So this is the kind of structure that you might be looking for. As you can see, I'm overloading the multiply method, since I can either call multiply with no arguments, or call multiply with one argument (an integer).

public class MyClass {
    ...
    public void multiply() {
        ...
    }
    public int multiply(int i) {
        ...
    }
}

Hopefully I was able to help =P

BatuhanBatuhan (1)

@eankeen

Thank you very much for the answer. The problem is both methods should be taking the same argument. That's why overloading doesn't work. Actually the return type is not a part of the method signature in java. It is only the specifiers and name and the arguments. This is the desired output.

1 Imaginary im1 = new Imaginary(3 ,4) ;
2 Imaginary im2 = new Imaginary( -2 , 10) ;
3
4 im1.add ( im2 ) ; // result im1 = 1 + 14 i
5 Imaginary im3 = im2. add( im1) ; // result im3 = 1 + 14 i

See both functions are invoked with the same name and takes the same arguments. Overloading unfortunately is not the answer here. I am guess Professor expects us to use polymorphism or interfaces or generic or idk.

I mean I will have to study all those anyway but the homework due is before the final :P better get this done first but still don't know where to begin. I guess I will have to finish all hundreds of pages of slides then hopefully have an idea about the solution lol

 
eankeen (658)

@BatuhanBatuhan Ohh,
Yeah I didn't know that the methods should take the same parameters. That would have been good to know haha. Yeah the only other way I can think of some sort of solution is through simple inheritance. The parent and child can have multiply and you can call super.multiply() from within the child. And yah I guess it's unfortunate that Java type signatures doesn't include the return type. It does make a bit of sense why that's the case though. Well good luck on finding a solution :)