i have class called animal
. given animal a
, a.number_of_legs
should 4.
i have class called human
inherits animal
. given human h
, h.number_of_legs
should 2.
how set number_of_legs
property?
here's have far:
class animal { int number_of_legs = 4; } class human : animal { int number_of_legs = 2; }
but if take arbitrary animal , ask how many legs has, answer 2:
animal x = new animal(); animal y = new human(); x.number_of_legs // --> 4 y.number_of_legs // --> 4
i understand new human
being treated animal
because variable y
stores animal
.
how set number_of_legs
property x.number_of_legs
4 , y.number_of_legs
2?
first of all, should using actual c# properties publicly accessible values this, not public fields.
mark property virtual
in base class can overridden in derived classes.
public class animal { // default, animals have 4 legs. public virtual int numberoflegs { { return 4; } } }
then override
in derived class provide different implementation.
public class human : animal { // humans have 2 legs. public override int numberoflegs { { return 2; } } }
Comments
Post a Comment