Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow different parameters without overloading method?

SOLVED: Thank you everyone for the help, I ended up overriding the method in Person like a couple of you said. My problem was that Character didn't even have doSomething, so what I ended up doing was simply adding doSomething to character and returning nothing. This is because I only had to worry about the a(a person).doSomething(b)(a character) case.

So, I have a method that takes two parameters, Character a and Character b.

 public static void giveMessage(Character a, Character b)

I want this method to also work if the parameters are Person a (which is a subclass of character), Character b

 public static void giveMessage(Person a, Character b)

I know I can do this by overloading the method, but it's followed by around 15 lines of code. So if I were to overload it 3 times it would become lengthy. I don't really have a problem with doing this, I'm just wondering if there is an easier way.

More info:

giveMessage(Character a, Character b){
    if(a instanceof Person){
       a.doSomething(b) 

doSomething is only found in Person, so it gives me an error that it can't find it in Character.

like image 562
Howcan Avatar asked Jul 19 '26 16:07

Howcan


1 Answers

public static void giveMessage(Character a, Character b)

should work for Persons because its an implicit cast

http://en.cppreference.com/w/cpp/language/implicit_cast (I know its c++ but this will work for java too)

it will automatically cast a person to a character

like image 140
Florian Groetzner Avatar answered Jul 22 '26 06:07

Florian Groetzner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!