Intern
How to fill the attributes of a class?
sobes.tech AI
Answer from AI
- Using setters. The most common way, providing data validation.
- Constructor. Allows initializing attributes when creating an object.
- Direct access. Applicable for public attributes, but considered bad practice (violates encapsulation).
- 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;
}