I have a class called Animal
. For any given animal a
, a.number_of_legs
should be 4.
I have a class called Human
which inherits from Animal
. For any given human h
, h.number_of_legs
should be 2.
How do I set up the number_of_legs
property?
Here's what I have so far:
class Animal {
int number_of_legs = 4;
}
class Human : Animal {
int number_of_legs = 2;
}
But if I take some arbitrary animal and ask how many legs it has, the answer is always 2:
Animal x = new Animal();
Animal y = new Human();
x.number_of_legs // --> 4
y.number_of_legs // --> 4
I understand that this new Human
is being treated as an Animal
because the variable y
stores an Animal
.
How do I set up the number_of_legs
property so that x.number_of_legs
is 4 and y.number_of_legs
is 2?