import ballerina/io;
type Person object {
    public string name = "";
    public int age = 0;
    public Person? parent = ();
    private string email = "default@abc.com";
    string address = "No 20, Palm grove";
};public function main() {
    Person p1 = new;
    io:println(p1.age);    Person p2 = new();
    io:println(p2.age);
    Person p3 = new Person();
    io:println(p3.age);
}

Object

Objects are a behaviourial type. An object is a combination of public, private, and module-level visible fields along with a set of associated functions (called methods) that can be used to manipulate the fields. This allows you to define custom-behavioural data types.

import ballerina/io;
type Person object {
    public string name = "";
    public int age = 0;

Defines an object called Person. It contains public, private, and module-level visible fields along with their types. For fields, the default value must be specified if an explicit object initializer method is not defined.

    public Person? parent = ();

If you need to have a field with its own type, you need to make that field defaultable (i.e., able to specify a default value). Here, the parent field is made defaultable by allowing it to have nil as a value.

    private string email = "default@abc.com";

Private fields are only visible within the object and its functions.

    string address = "No 20, Palm grove";
};

Protected fields (i.e., no access modifiers) are visible only within the same module.

public function main() {
    Person p1 = new;
    io:println(p1.age);

There are three ways to initialize a Person object.

    Person p2 = new();
    io:println(p2.age);
    Person p3 = new Person();
    io:println(p3.age);
}

This type of initialization is useful when you cannot determine the type of the object to be created based on the context (e.g., when the left hand side is a union of object types).

# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `ballerina run` command.
$ ballerina run objects.bal
0
0
0