Sobes.tech
Intern

How to fill the attributes of a class?

sobes.tech AI

Answer from AI

  1. Using setters. The most common way, providing data validation.
  2. Constructor. Allows initializing attributes when creating an object.
  3. Direct access. Applicable for public attributes, but considered bad practice (violates encapsulation).
  4. Reflection API. Allows setting private attribute values at runtime, used cautiously.

Example with setters:

public class Person {
    private String name;
    private int age;

    public void setName(String name) {
        if (name != null && !name.trim().isEmpty()) {
            this.name = name;
        }
    }

    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        }
    }

    // Getters for attribute access
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Example with constructor:

public class Car {
    private String make;
    private String model;

    public Car(String make, String model) {
        this.make = make;
        this.model = model;
    }

    // Getters and possibly setters
}

Example of direct access (not recommended):

public class Animal {
    public String species;
}