Howcan
Howcan

Reputation: 313

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.

Upvotes: 3

Views: 483

Answers (1)

Florian Groetzner
Florian Groetzner

Reputation: 512

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

Upvotes: 4

Related Questions