Why can't I access class fields from outside the class in EK9?
← Classes and OOP · Ref: Q882
ALL class fields are private. Always. There is no 'public' or 'protected' modifier for fields in EK9's grammar — it does not exist.
To expose state, write a method:
describe()
<- rtn as String: `${userName} <${email}>`
Record fields are the opposite — ALL public. That is the key difference:
- CLASS: fields private, has methods — for objects with behaviour
- RECORD: fields public, no methods — for pure data
You cannot write 'public name as String' on a class. You cannot write a method on a record. The compiler enforces this separation.
To copy field values, use ':=:' in a constructor:
MyClass()
-> initialName as String
name :=: initialName
See Q97 for class vs record. See Q95 for field visibility. See Q876 for record basics.
Example
defines module qa.classes.fields.private defines record Address street <- String() city <- String() Address() -> s as String c as String street :=: s city :=: c operator <=> as pure -> arg0 as Address <- rtn as Integer: street <=> arg0.street default operator defines class Person personName <- String() homeAddress <- Address("", "") Person() -> pName as String addr as Address personName :=: pName homeAddress :=: addr //Method exposes state — fields are private location() <- rtn as String: `${personName} lives in ${homeAddress.city}` default operator ? defines program FieldVisibility() stdout <- Stdout() //Record fields are public addr <- Address("123 Main", "Springfield") stdout.println(addr.city) //Class fields accessed via methods person <- Person("Steve", addr) if person? stdout.println(person.location())
Other ways to ask this
- Are all EK9 class fields private?
- How do I expose class state in EK9?
- What is the visibility of fields in EK9 classes vs records?
Coming from another language?
Java: public/private/protected on fields. Python: convention-only _prefix. Kotlin: var/val with getters. EK9: class fields ALWAYS private, record fields ALWAYS public — no modifier needed or allowed.
Keywords: visibility, private, access, record, class, public, field, method