static void Main(string[] args) { // Inheritance Shape shape = new Shape(); Console.WriteLine(shape.Area());// returns 0 as it invokes the Area method inside the shape class Rectangle rectangle = new Rectangle(15, 5); Console.WriteLine(rectangle.Area());// returns 0 Even though rectangle does not have a method called area, it works because it inherited the method from the base class Shape. This is inheritence // Method override at work - polymorphism Shape x = new Shape(); Console.WriteLine(x.Area()); Square square = new Square(10); Console.WriteLine(square.Area());// returns 100 Square's area method is invoked, override at work // Another example of polymorphism Shape z = new Rectangle(5, 2); Console.WriteLine(z.Area()); // returns 10 // this works because you can supply a child instance in place of a parent. This is polymorphism // // because area is a virtual method, at run time, CLR will realise that x is an instance of Rectangle, it will invoke the method from Rectangle class }
static void Main(string[] args) { Console.WriteLine("Hello Polimorfismo!"); Console.WriteLine("Es la habilidad de presentar la misma interface de diferente forma."); Console.WriteLine("Type Polimorfismo!"); Console.WriteLine("1. Static / Compile time"); TestData dataClass = new TestData(); int add2 = dataClass.Add(45, 34, 67); int add1 = dataClass.Add(23, 34); Console.WriteLine("int add2 = dataClass.Add(45, 34, 67);"); Console.WriteLine("int add1 = dataClass.Add(23, 34);"); Console.WriteLine("2. Dynamic / Runtime"); List <Shape> ShapeList = new List <Shape>(); Shape circle = new Circle(); Shape Rectangle = new Rectangle(5.3, 3.4); Shape Square = new Square(); ShapeList.Add(circle); ShapeList.Add(Rectangle); ShapeList.Add(Square); Console.WriteLine("Area:" + circle.Area()); Console.WriteLine("Area:" + Rectangle.Area()); Console.WriteLine("Area:" + Square.Area()); foreach (Shape shape in ShapeList) { Console.WriteLine(shape.Draw()); } }