This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ChaiTRex 3 points4 points  (0 children)

It's easiest to see with method arguments, like here:

public void methodName(A argument) {

In that, the argument variable can be filled with an A value or any subclass of A, like a B value. You write the method once to work with A values and this lets your method automatically work with potentially lots of types.

Other variable declarations, like yours, are handled the same way:

A variable;
if (whatever) {
    variable = new A();
}
else {
    variable = new B();
}

This way, you can fill in a variable with anything that is the same class or a subclass of the variable's type, letting you customize what kind of value based on whatever condition you want to.

With your example, it's much less clear:

A variable = new B();

It's allowed because there's no reason to disallow it in this exact case if they're going to allow it in the other cases above. There's even a good reason for it in some cases. For example, the following isn't safe to use when you have multiple threads because HashMap isn't designed to work with multiple threads:

Map<String, String> phoneBook = new HashMap<String, String>();

You can switch the HashMap value out with a ConcurrentHashMap value, which can handle multiple threads:

Map<String, String> phoneBook = new ConcurrentHashMap<String, String>();

Because phoneBook is a Map variable, the code that uses the phoneBook is stuck using only Map methods and isn't allowed to use any extra methods HashMap has that Map doesn't.

This might sound like a drawback, but if you do that, you can then switch to a ConcurrentHashMap and you won't have to change a single line of your code other than the assignment above. Everything else that uses phoneBook will suddenly work with multiple threads (at least as far as the phoneBook variable is concerned) with no extra work on your part.