22222222
22222222

Reputation: 581

Dynamic Method Binding in Java

With this code

public static void doSomething(Animal arg)
{
...
}

Which one of the following is more correct? (They both compile and run fine.) Is there a difference?

public static void main(String[] args)
{
Animal fido = new Dog();
doSomething(fido);
}

or

public static void main(String[] args)
{
Dog fido = new Dog();
doSomething(fido);
}

I don't believe it matters, but is one more conventional? Thanks.

Upvotes: 1

Views: 877

Answers (3)

nerdytenor
nerdytenor

Reputation: 431

As a rule of thumb, I like to keep types as general as possible - it is a form of information hiding. Even when a type is only used internally to a class or method, keeping the type general reduces the number of things you have to think about when an instance of that type is referenced later in the code.

Upvotes: 0

Mark Elliot
Mark Elliot

Reputation: 77024

It depends on your use case. If you need to access the semantics of Dog, then you should use Dog, if you only need the semantics of Animal, and you want the generality of Animal, you should use Animal.

Upvotes: 2

MByD
MByD

Reputation: 137272

It depends on your use of this object later in the code, if this might hold other Animal in the rest of the code, then keep it Animal, for the call to this method (doSomething), it doesn't matter (since a Dog is an Animal).

Upvotes: 3

Related Questions