TAGS :Viewed: 20 - Published at: a few seconds ago

[ Java. Why is useful to do this: Animal bear = new Bear(); ]

I see why it's a legal declaration, but why would it be useful?

How is this different from just going:

Bear bear = new Bear(); //?

What can I do with the object Animal bear = new Bear(); that I can't do with the latter?

Attempt at clarification:

What's the practical diference between declaring something like this:

A. SuperClass x = new SubClass();


B. SubClass x = new SubClass();

What can you do with the object in A that you can't do with B? Why would you want to declare an object like this at all?


Answer 1

In general, it's desirable to have loose coupling whenever possible. In part, this means that your code should know as little as possible about the objects it uses. If it is sufficient for your code to know that it's an Animal, then why should you let it know it's a Bear? Next week you might want to run your code with a Chicken.

By restricting yourself to the interface exposed by Animal, you've now made it easy to drop in any other particular animal in its place and you know that you haven't used any Bear-specific methods.

Answer 2

To achieve polymorphism and to write generic code for all the Animals rather than specific to bear.

So, Animal animal = new Bear() and we can use the same reference we can use to point to other different animals.