Phase 11: Complete Anatomy of a Class in Code
See how a production-grade class is constructed line-by-line in Java, from private instance fields to constructors, getters, setters, and instance methods.
The Complete Class Code Structure
public class Student {
// 1. Private Instance Variables (Encapsulated Fields)
private String studentId;
private String fullName;
private double gpa;
// 2. Static Variable (Class-level field shared across all instances)
private static int totalStudentsEnrolled = 0;
// 3. Default Constructor (No parameters)
public Student() {
this.studentId = "UNKNOWN";
this.fullName = "Anonymous";
this.gpa = 0.0;
totalStudentsEnrolled++;
}
// 4. Parameterized Constructor (Overloaded)
public Student(String studentId, String fullName, double gpa) {
this.studentId = studentId;
this.fullName = fullName;
setGpa(gpa); // Uses setter for validation!
totalStudentsEnrolled++;
}
// 5. Getters (Accessors)
public String getStudentId() { return this.studentId; }
public String getFullName() { return this.fullName; }
public double getGpa() { return this.gpa; }
// 6. Setters (Mutators with Validation Invariants)
public void setGpa(double gpa) {
if (gpa >= 0.0 && gpa <= 4.0) {
this.gpa = gpa;
} else {
System.err.println("Invalid GPA range!");
}
}
// 7. Instance Method (Behavior)
public boolean isDistinctionStudent() {
return this.gpa >= 3.5;
}
// 8. Static Method (Utility)
public static int getTotalStudentsEnrolled() {
return totalStudentsEnrolled;
}
}