NEW INTERVIEW QUESTIONS.COM
MICROSOFT INTERVIEW QUESTIONS
C# INTERVIEW QUESTIONS DETAILS
NewInterviewQuestions.com - Home for World's Largest Interview Questions Website.
A D V E R T I S E M E N T
Question |
How we can use inheritance and polymorphisms in c# programming?
|
Answer
|
Inheritance in C# is similar to cpp, if you are familiar to cpp, the only difference is you dont inherit a class in public or protected mode, the way to inherit a class is Class Base { protected int length, breadth; public Base(int a, int b) { this.length = a; this.breadth = b; } public virtual int Show() { Console.WriteLine(Length of a rectangle is {0} and breadth is {1}, length, breadth); } } Class Derived: Base // The way to inherit a class in C# { public Derived(int l, int b, string color): base(l, b) // call Base constructor { this.color = color; } // an overridden method beacuse in the derived method we can // change the behaviour, This is a kind on polymorphism. public override int Show() { base.Show(); Console.WriteLine("Color of the rectangle is " color); } public string color; } Class Tester { public static void Main() { Base b = new Base(10, 20); Derived d = new Derived(30, 40, "Red" ); b.Show(); d.show(); } }Output: Length of a rectangle is 10 and breadth is 20 Length of a rectangle is 30 and breadth is 40 Color of the rectangle is RedI hope this will make you a bit clear about Inheritance and polymorphism.
© NewInterviewQuestions.com
|
If you have the better answer, than send it to us. We will display your answer after the approval.
Rate the above answer. Help us to know about the answer.
Please Note: We keep on updating better answers to this site. Subscribe to our newsletter to get notified when better answer is posted.
|