How do I create a class with a constructor and methods in EK9?
← Classes and OOP · Ref: Q874
Classes have private fields (initialised with '<-'), constructors, and methods. Fields are always private in classes. Use ':=:' (copy) to assign constructor parameters to fields. Add 'default operator ?' at the end for the isSet check.
See Q93 for class basics. See Q94 for constructors. See Q96 for operators. Use 'ek9 -h class' for syntax.
Example
defines module qa.classes.with.methods defines class BankAccount ownerName <- String() balance <- 0.0 BankAccount() -> owner as String initialBalance as Float ownerName :=: owner balance :=: initialBalance deposit() -> amount as Float balance += amount getBalance() <- rtn as Float: Float(balance) describe() <- rtn as String: `${ownerName}: balance ${balance}` default operator ? defines program BankDemo() stdout <- Stdout() account <- BankAccount("Steve", 100.0) account.deposit(50.0) if account? stdout.println(account.describe()) stdout.println(`Balance: ${account.getBalance()}`)
Other ways to ask this
- Show me a basic EK9 class with state and behaviour
- How do I define a class with fields and methods?
- EK9 class example with constructor
Coming from another language?
Java: public/private fields. Python: self.field. Kotlin: data class. EK9: fields always private, '<-' initialises, ':=:' copies.
Keywords: private, class, behaviour, field, constructor, state, method