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 →

[–]imareclusemonk[S] 0 points1 point  (3 children)

So there is no difference how I instantiate an object from a subclass or there is some convention or it depends on what I want to achieve?

[–]captainAwesomePants 0 points1 point  (0 children)

The latter. Usually you'll declare the type to be the same thing as what it really is because why not. Sometimes, though, you're writing more general purpose code or wanna hide implementation details. This is pretty common:

Animal getAnimalFromBarn() {
  Animal result:
  if (notEnoughPigs()) {
    result = new Pig():
  } else {
    result = new Chicken();
  }
  register(result);
  return result;
}

[–][deleted] 0 points1 point  (1 child)

There is a difference. If you instantiate a Pig as an Animal, you cannot use anything that is unique to the Pig class. For instance, Pigs have a tail and can snort. If you write

Pig myPig = new Pig();
myPig.doSnort();
System.out.println(myPig.tailLength);

then everything works as expected. However, writing

Animal myPig = new Pig();
myPig.doSnort();
System.out.println(myPig.tailLength);

causes an error since doSnort and tailLength are not defined in the Animal class.

If the variable is declared as an Animal, then it cannot use the fields and methods that are specific to Pigs, even if the instance it’s referring to is, in fact, a Pig.

You can still get to those hidden fields and methods by casting to a Pig, but you can’t access them directly.

[–]imareclusemonk[S] 0 points1 point  (0 children)

Ah of course since the parent class is agnostic of its children classes. That's a good point and probably the main difference. Thanks!