Inheritance and Polymorphism

Inheritance

In DolphinDB, only single inheritance is supported, meaning a class can inherit from only one parent class. An object's type is determined by its behavior rather than its inheritance, and a class can adopt multiple classes' features by implementing the necessary methods and attributes, even without multiple inheritance.

In DolphinDB, class inheritance allows a derived class to inherit the attributes and methods of a base class. However, member variables in the derived class must be unique and cannot duplicate those in the base class.

class Base {
    alpha :: INT
    def Base(a) {
        alpha = a
    }
    def method() {
        print(alpha)
    }
}
class Derived : Base {
    beta :: INT
    def Derived(a, b) {
        alpha = a
        beta = b
    }
    def method2() {
        method()
        // Use attributes from the base class
        print(alpha + beta)
    }
}
x = Derived(1, 2)
x.method2()
// output: 1 3

In a derived class, you can call the base class constructor.

class Base {
    alpha :: INT
    def Base(a) {
        alpha = a
    }
    def method() {
        print(alpha)
    }
}
class Derived : Base {
    beta :: INT
    def Derived(a, b) {
        Base(a)
        beta = b
    }
    def method2() {
        method()
    }
}
x = Derived(1, 2)
x.method2()
// output: 1

Polymorphism

In class definitions, methods behave similarly to virtual functions in C++, supporting polymorphism. When a method in the derived class has the same name as one in the base class, the derived class method overrides the base class method. To correctly override a method, the method in the derived class must have the same function signature (parameter list and return type) as the method in the base class.

class Base {
    def Base() {}
    def virtualMethod() {}
    def doSomething() {
        virtualMethod()
    }
}
class Derived : Base {
    alpha :: INT
    def Derived(a) {
        alpha = a
    }
    // override
    def virtualMethod() {
        print(alpha)
    }
}
d = Derived(100)
d.doSomething()
// output: 100