Getters, Setters, and Interoperability
Kotlin and Java handle class-level variables quite differently. Java uses fields and typically gates access via accessor and mutator methods. Kotlin, as you have seen, features properties, which restrict access to backing fields and may automatically expose accessors and mutators.
In the last section, you added a public hitPoints field to Jhava. This worked to illustrate type mapping, but it violates the principle of encapsulation – so is not a good solution. In Java, fields should be accessed or mutated using getter and setter methods. Getters can be used to access data, and setters can be used to mutate data.
Make hitPoints private and create a getter method so hitPoints can be accessed but ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access