Class Statement

Declares the name of a class and defines its implementation.

Syntax

[ modifier ] Class class_name [ < type_list > ] [ Is base_class ] [ Does trait_name ]...
    [ Where generic_constraints ] ...
    [ statements ]
End [ Class ]

Parts

modifier
Optional, between square brackets:
  • Abstract – The class must be extended by a class that is not Abstract.
  • Final – The class cannot be extended.
class_name
Necessary identifier that names the class.
type_list
Optional – One or more identifiers with commas between each, all between angle brackets (< >).
base_class
Optional name of another class from which this class inherits methods and properties.
Does
Optional, repeatable – Specifies which traits a class implements.
trait_name
The name of a trait, a way to define behavior. See Does Clause (Traits) for more information.
Where
Optional, repeatable – Specifies constraints to put on type arguments. Requires a type_list. You can put one at the end of the first line. Or you can have one or more, each on different lines, before any statements.
generic_constraints
One or more constraints on a generic parameter, with a comma between each. See Where Clause (Generics) for more information.
statements
Optional statements that define the members of the class.
End
Completes the statement. You can also use End Class.

Instructions

A Class statement defines a data type known as a class. Classes are fundamental building blocks in object-oriented programming (OOP). See Objects and Classes for more information.

You can put a Class only in certain contexts. These contexts include Program and Library modules, other classes, and Object and Trait declarations. You cannot put a class in a procedure. See Declaration Contexts and Default Access Levels for more information.

Permitted members

Examples

Example 1

Program ClassExample
Require IO

Class Person
    Var my_name As String, my_age As UInt16
    Constructor name As String, age As UInt16
        my_name = name
        my_age = age
    End Constructor
    Property Name As String
    Get
        Return my_name
    End Property
    Property Age As UInt16
    Get
        Return my_age
    End Property
End Class

Person #a, "Alice", 24
Person #b, "Bob", 42

PrintLine #a.Name & " is " & #a.Age
PrintLine #b.Name & " is " & #b.Age

' Output:
' Alice is 24
' Bob is 42

See also