Poorna
Poorna

Reputation: 329

Inheritance and abstraction in Ballerina

I am working on a project in Ballerina where I have two different implementations for a class. I want to create an abstract class that defines some common methods (can have both abstract and regular methods), and then have two separate implementations for each type of the implementations. My question is how can I create an abstract class in Ballerina that defines common methods and have separate implementations for the abstract class and how does inheritance work in Ballerina?

Upvotes: 2

Views: 63

Answers (1)

Poorna
Poorna

Reputation: 329

Object type inclusion in Ballerina can be used to have an object type as an "interface" and include it in the classes to enforce the including classes to implement the methods. You can find more information about this method here. https://ballerina.io/learn/by-example/object-type-inclusion/

Ballerina does not have implementation inheritance. i.e.Allowing a subclass to inherit the implementation of methods in a superclass. In Ballerina, it is possible to use composition to achieve a similar objective as implementation inheritance.

Following code demonstrates a object type inclusion and composition based implementation for the problem:

public type IType distinct object {
    function methodOne() returns ReturnTypeOne;

    function methodTwo() returns ReturnTypeTwo;
};

public class CommonTypeImplementation {
    *IType;

    function methodOne() returns ReturnTypeOne {
        io:println("This is calling common-impl [Mehod1]");
        return {};
    }

    function methodTwo() returns ReturnTypeTwo {
        io:println("This is calling common-impl [Mehod2]");
        return {};
    }
}

public class InmemoryTypeImplementation {
    *IType;

    private final CommonTypeImplementation commonImpl;

    public function init() {
        self.commonImpl = new();
    }

    function methodOne() returns ReturnTypeOne {
        return self.commonImpl.methodOne();
    }

    function methodTwo() returns ReturnTypeTwo {
        io:println("This is calling in-memory-impl [Mehod2]");
        // implement customized logic here
        return {};
    }
    
}

Upvotes: 2

Related Questions