Ensuring that a system contains valid data is a core responsibility of an object. This project demonstrates Defensive Programming through encapsulation. By making the currentAge field private and providing a "Smart Setter", we prevent the student's age from ever becoming negative. The object acts as a gatekeeper, rejecting invalid inputs and providing feedback while maintaining its internal consistency.
- Encapsulated State: The
currentAgefield is strictly private. - Validation Logic: Implemented an
if-elsecheck within the setter to filter out negative values. - Feedback System: The program provides a specific error message when a validation rule is violated.
- State Persistence: Verified that invalid updates do not overwrite existing correct data.
- Java 8+ (Encapsulation, Setters with Validation, Logical Branching)
- SchoolStudent: The Model. Contains the business logic for age validation.
- Solution: The Controller. Tests the "attack" (negative age) and the "valid update".
Attention! The student's age cannot be negative. The value has not been updated.
10
15
Project Structure:
JavaBasics_Task_255/
├── src/
│ └── com/yurii/pavlenko/
│ ├── SchoolStudent.java
│ └── Solution.java
└── README.md
Code
package com.yurii.pavlenko;
public class Solution {
public static void main(String[] args) {
SchoolStudent student = new SchoolStudent(10);
student.setCurrentAge(-5);
System.out.println(student.getCurrentAge());
student.setCurrentAge(15);
System.out.println(student.getCurrentAge());
}
}package com.yurii.pavlenko;
public class SchoolStudent {
private int currentAge;
public SchoolStudent(int age) {
this.currentAge = age;
}
public int getCurrentAge() {
return currentAge;
}
public void setCurrentAge(int potentialAge) {
if (potentialAge < 0) {
System.out.println("Attention! The student's age cannot be negative. The value has not been updated.");
} else {
this.currentAge = potentialAge;
}
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT