super

Summary

'super' refers to the base class instance. The 'super' keyword can also be used to invoke a class constructor or access non-static members of a base class.

Syntax

super([ argument1[, argument2[, [...] argumentN ] ] ])
super[.member]

Parameters

argumentN
Any legal expression to supply as an argument to the base class constructor call.
member
A member of the base class whose instance the 'super' keyword refers to.

Description

The super keyword refers to the base class instance. The super keyword can only be used inside derived classes.

Accessing Members of Base Class

The non-static members of a base class, such as its fields and methods, can be accessed from a derived class using super:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import System;
 
class Person
{
    public void sayHello() {
        Console.log("Hello!");
    }
}
 
class Employee : Person
{
    public void sayHello() {
        // Use 'super' to access 'sayHello' defined in the base class
        super.sayHello();
    }
}

Calling Constructors

The super keyword can also be used to call a non-static constructor of a base class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Person
{
    private string name;
 
    public Person() {}
    public Person(string name) {
        this.name = name;
    }
}
 
class Employee : Person
{
    public Employee() {
        super(); // Call the base class constructor that takes no arguments
    }
    public Employee(string name) {
        super(name); // Call the base class constructor that takes one string argument
    }
}
 
new Employee("Bob");

For overloaded constructors, the compiler will attempt to match the argument types with the constructor parameter types. If there are no matching constructors, a compile-time error will be raised. If there is more than one possible match, the compiler will use the most specific overload first before attempting to convert argument types. See the function overloading page for more information on overloading is handled.

Examples

Returning Base Class Object
1
2
3
4
5
6
7
class Foo {}
class Bar : Foo
{
    public Foo getFoo() {
        return super;
    }
}

See Also

Share

HTML | BBCode | Direct Link