Classes

Classes are another big chunk of code that can have states and functions called methods, They are an object by themselves that provide a blueprint for objects.

Creating a class.

Creating a class is done by the class keyword followed by a name, then a body.


class Alive {
    // class.
}

// instance object.
let person = Alive(); 
                    


Constructor.

A constructor is a method that is invoked when creating a new instance of a class, in other words 'calling' a class will just invoke the constructor method which is init


class Dead {
    //constructor
    init(final_words) {
        final_words + "!";
    }
}

Dead("im not dead.");
                    


Attributes.

Attributes are defined in the constructor method and can be accessed through instances. Creating an attribute can be done with the this keyword which references to the instance you are accessing, followed by a name and then the value of the property. They can also be created on the object directly.


class Player {
    // constructor
    init (name) {
        // new attribute
        this.name = name;
    }
}

let v = Player("Mr.P");
v.name; //Mr.P
                    


Methods.

Methods are functions defined within a class and can be called and also accessed.


class Player {
    init (name) {
        this.name = name;
    }

    // method.
    getName () {
        return this.name;
    }
}

let v = Player("Mr.P");
v.getName(); //Mr.P
                    


Access Levels.

Access levels offer a class the ability to hide or expose a portion of the functionality it implements. In Pa You can either make it inaccessible by making it private or accessible to make it available for use, this ability is only possible to methods and attributes of an instance.

By default, every attribute & method is public.
Creating a private attribute can be done by the private keyword then the name of the attribute comes after, and finally a value.


class Player {
    init (name) {
        // private attribute.
        private name = name;
    }

    // public method.
    getName () {
        return this.name;
    }
}

//instance
let x = Player("John");

//public method use.
x.getName(); //John

//private property use.
x.name //error. 
                


Private methods work the same mostly.


class Creature {
    init (health) {
        // private property.
        private hp = health;
    }

    // private method.
    private getHealth () {
        return this.hp;
    }

    printHealth() {
        print(this.getHealth());
    }
}

let monster = Creature(100);

//public method use.
monster.printHealth(); //100

//private method use
monster.getHealth(); //error.