import ballerina/io;
type Person abstract object {
    public int age;
    public string firstName;
    public string lastName;
    function getFullName() returns string;    function checkAndModifyAge(int condition, int a);
};
type Employee object {
    public int age;
    public string firstName;
    public string lastName;
    function __init(int age, string firstName, string lastName) {
        self.age = age;
        self.firstName = firstName;
        self.lastName = lastName;
    }
    function getFullName() returns string {
        return self.firstName + " " + self.lastName;
    }    function checkAndModifyAge(int condition, int a) {
        if (self.age < condition) {
            self.age = a;
        }
    }
};public function main() {
    Person p = new Employee(5, "John", "Doe");
    io:println(p.getFullName());
    
    p.checkAndModifyAge(10, 50);    io:println(p.age);
}

Abstract Objects

In Ballerina, objects can be abstract. Abstract objects only describe the fields and the signatures of the methods. An abstract object cannot be initialized and does not have a default value.

import ballerina/io;
type Person abstract object {
    public int age;
    public string firstName;
    public string lastName;

Defines an abstract object called Person. It should only contain fields and method declarations. An abstract object cannot have an initializer or method definitions.

    function getFullName() returns string;

Method declarations can be within the object. However, the method cannot have a body.

    function checkAndModifyAge(int condition, int a);
};
type Employee object {
    public int age;
    public string firstName;
    public string lastName;

Defines a non-abstract object called Employee, which is structurally equivalent to Person. A non-abstract object cannot have any methods without a body.

    function __init(int age, string firstName, string lastName) {
        self.age = age;
        self.firstName = firstName;
        self.lastName = lastName;
    }

Non-abstract objects can have initializers.

    function getFullName() returns string {
        return self.firstName + " " + self.lastName;
    }

Methods should have a body.

    function checkAndModifyAge(int condition, int a) {
        if (self.age < condition) {
            self.age = a;
        }
    }
};
public function main() {

An abstract object type cannot be initialized. It does not have an implicit initial value.

    Person p = new Employee(5, "John", "Doe");
    io:println(p.getFullName());
    
    p.checkAndModifyAge(10, 50);

Initializes a value using the non-abstract object Employee, and then assigns the value to the abstract object type variable.

    io:println(p.age);
}
# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `ballerina run` command.
$ ballerina run abstract_objects.bal
John Doe
50