Junior — Middle
How can constraints be set in a system or in code?
sobes.tech AI
Answer from AI
Restrictions in the system or code are set to control the behavior of the program and prevent errors. In Java, this can be done in several ways:
- Using access modifiers (
private,protected,public) to limit the visibility of classes and their members. - Validating input data with conditional statements or exceptions to prevent incorrect values.
- Using final for variables to make them immutable.
- Restrictions at the business logic level, such as checking number ranges.
Example of restricting a variable's value:
public class User {
private int age;
public void setAge(int age) {
if (age < 0 || age > 150) {
throw new IllegalArgumentException("Age must be between 0 and 150");
}
this.age = age;
}
}
Thus, restrictions help ensure the correctness and safety of the program.