Sobes.tech
Junior — Middle

How can the standard behavior of a property be implemented in a class?

sobes.tech AI

Answer from AI

In Android (Java/Kotlin), the standard behavior of a property in a class can be implemented using getters and setters. This allows controlling access to the field and adding additional logic when reading or writing the value.

Example in Kotlin using standard getters and setters:

class User {
    var name: String = ""
        get() = field.toUpperCase()  // returns the name in uppercase when reading
        set(value) {
            field = value.trim()       // trims spaces when setting
        }
}

Here, field is a special property that stores the value of the property. If you do not override the getter and setter, the behavior will be standard — simply reading and writing the value.

In Java, it is common to create a private field and public get/set methods:

public class User {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name.trim();
    }
}

Thus, the standard behavior of a property is encapsulation of a field using access methods.