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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import 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
1
2
3
4
5
6
7
8
9
10
11
12
abstract class Shape
{
    public abstract int area();
}
class Rectangle : Shape
{
    private int length, width;
 
    public override int area() {
        return length * width;
    }
}

See Also

Share

HTML | BBCode | Direct Link