#Redundant code?

16 messages · Page 1 of 1 (latest)

mossy urchin
#

Two classes exist: Animal and Tiger (Animal is the super class, and Tiger is a subclass)

Now, we make an object Animal a = new Tiger();

Why does this Animal a not have the capabilities of a Tiger class?

If I declare Animal a = new Tiger();, this is practically the same thing as Animal a = new Animal(); since Animal a = new Tiger(); strips away all the extra functions and variables that Tiger has (I believe because the refrence object is Animal and not Tiger)

So what's the point here? Why do this? Why would I declare Animal a as Tiger, when it strips away all Tiger attributes and methods?

calm tulipBOT
#

This post has been reserved for your question.

Hey @mossy urchin! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

tawny cipher
#

Animal a gives the type to the variable, regardless of the actual value

#

it means a can be assigned any Animal

#
Animal a = new Tiger();
if (Math.random() < 0.5) { // 50/50 chance
  a = new Animal();
}
a.roar(); // should or should not work?
```we don't know if a would still be a Tiger at compiletime, just that it's an animal
in practice, that possible switch could be deep inside logic, and you'd have to apply it to every extensible type, so it just isn't feasible (nor intuitive to the developer) to do it
mossy urchin
#

But if you're making an Animal a, which uses Tiger's constructor. The object a wouldn't have Tiger capibilites?

#

What's the point of this?

#

To store Tiger into an array of Animal?

tawny cipher
#

if you tell java that the value inside is indeed a tiger, then you can use it without issues (assuming that it is actually a tiger)

Animal a = new Tiger();
Tiger definitelyTiger = (Tiger) a;
definitelyTiger.roar();
#

in this case, if a happened to not be a Tiger, it would incur a ClassCastException, for which you can guard with instanceof

#
Animal a = new Tiger();
if (a instanceof Tiger tiger) {
  tiger.roar();
}
#

the point of this is to allow polymorphism, which says that subclasses can be used as if they were the parent
String could be used as if it were an Object
Integer could be used as if it were a Number or Object
Tiger could be used as if it were an Animal or Object

#

but this doesn't apply in the opposite direction

#

consider maybe you were making a zoo, and you needed some kind of Cage to hold an animal:

class Cage {
  Animal animal;
}
```for any cage, we can know that it holds an `Animal`, but we don't know what kind
so if we had a cage with a `Bird`, that obviously wouldn't be able to `roar`
by the same logic, for any given `Animal`, we can't know if it can `roar` or not unless we check