Re: real world polymorphism
We responded at the same time, but don't use 'new' keyword in your derived class implementations. Use 'override' instead.
'new' hides the derived class' implementation. If you use 'new', then you can't do:
Human human = new Superhero();
You can, but then all human.Member calls will be calling Human versions instead of Superhero versions.
You must do:
Superhero human = new Superhero();
If you want to use the 'new' version of each implemented member.
The easy solution is to change 'new' to 'override' in your derived classes.
Then you can do:
Human human = new Superhero();
And human.Method will call the Superhero() overriden version instead of the base Human version.
Re: real world polymorphism
Quote:
Originally Posted by
sidhu688
ok so here is the program parts and the questions
protected new int power = 50; why the new keyword is used here ?
public int HumanPower { get { return base.power; } } // will this return the power of the base class?
public new int Power { get { return this.power; } } // is this used for returning power of the current object ?
Console.WriteLine("is human a human? " + human is Human);
Everything is coming false when i am running this code and a green line is coming below these and says the given expression is never of the provide ('oops_Concepts.Human) type ?
Console.WriteLine("memloo's human power: " + ((Human)memeloo).Power);
((Human).memeloo) what does this mean ?
Have you tried running the code? If not, try running the code and think about the output that you see. It might answer some of your questions.
Re: real world polymorphism
Quote:
Originally Posted by
sidhu688
public int HumanPower { get { return base.power; } } // will this return the power of the base class?
public new int Power { get { return this.power; } } // is this used for returning power of the current object ?
modify the code, run it and see it for yourself.
Re: real world polymorphism
Quote:
Originally Posted by
mariocatch
We responded at the same time, but don't use 'new' keyword in your derived class implementations. Use 'override' instead.
you're right. it was stupid here to use the "new". I'll correct it right away.
edit: corrected :)