InterviewSolution
| 1. |
What are virtual functions in C#? |
|
Answer» A virtual function is redefined in derived classes. It is usually used when more than the basic functionality of the function is required in the derived classes. So the virtual function has an implementation in the base class as well as in the derived classes as well. The virtual modifier cannot be used with the abstract, static, private and override modifiers. The virtual keyword is used in the base class to CREATE a virtual function. The override keyword is used in the derived classes to override the function. A program that demonstrates virtual FUNCTIONS in C# is given as follows: using System; namespace Demo { class Shape { public virtual double area() { return 0; } } class Square: Shape { private double side; public Square( double s) { side = s; } public override double area () { return (side * side); } } class Rectangle: Shape { private double length; private double breath; public Rectangle( double l, double b) { length = l; breath = b; } public override double area () { return (length * breath); } } class Circle: Shape { private double RADIUS; public Circle( double R) { radius = r; } public override double area () { return (3.14 * radius * radius); } } class Test { static void MAIN(string[] args) { Square s = new Square(3.5); Console.WriteLine("Area of Square = {0}", s.area()); Rectangle r = new Rectangle(7.0, 2.0); Console.WriteLine("Area of Rectangle = {0}", r.area()); Circle c = new Circle(4.0); Console.WriteLine("Area of Circle = {0}", c.area()); } } }The output of the above program is as follows: Area of Square = 12.25 Area of Rectangle = 14 Area of Circle = 50.24 |
|