override Summary The override modifier is used to override a virtual or abstract method. Syntax override member Parameters member The member to make 'override'. Description The override keyword specifies a new implementation or a virtual/abstract method inherited from a base class. It is also used for explicitly specifying the implementation for interface methods. A method cannot be overridden if: It is not a virtual, abstract, or interface method It is static It has a different access modifier It has a different return type, parameter type, parameter order, or method signature The override modifier specifies late binding. For early binding, use the overwrite modifier. Virtual Methods By default, methods are non-virtual and are resolved at compile time. If a derived class has a method with the same name as its base class, this is known as shadowing (or method hiding) and gets resolved at compile time. However, virtual methods are resolved at runtime. At runtime, when a virtual method is called, the runtime type of the invoking object is examined, and the overridden method of the most derived class is called. If no overridden methods are available, the original virtual method is invoked. Abstract Methods Abstract methods differ from virtual methods in that they do not have a base implementation. Therefore, derived classes must implement the abstract method (using the override keyword) before it can be used. Final Methods In addition, the final modifier can be applied to a class method to specify that the implementation of the method is finalized and cannot be further overridden by derived classes. Examples Iterating Array of Objects and Calling Overridden Functions 123456789101112131415161718192021222324252627282930313233343536373839404142434445import System; class Shape{ public virtual double area() { return 0; }} class Rectangle : Shape{ private int length, width; public Rectangle(int length, int width) { this.length = length; this.width = width; } public override double area() { return length * width; }} class Triangle : Shape{ private int base, height; public Triangle(int base, int height) { this.base = base; this.height = height; } public override double area() { return (base * height) / 2; }} Shape[] shapes = [ new Rectangle(5, 5), new Triangle(3, 4) ];foreach(Shape shape in shapes) { Console.log(shape.area());} // Output:// 25// 6 Implementing Abstract Methods 123456789101112abstract class Shape{ public abstract int area();}class Rectangle : Shape{ private int length, width; public override int area() { return length * width; }} See Also virtual abstract final class Share HTML | BBCode | Direct Link