'F' → Fullscreen
this. Step 1: Create a file named Student.java and type the following code:
class Student{ String name; int gradeLevel;
// No-argument constructor Student() { name = "Unnamed"; gradeLevel = 9; }
// Full-argument constructor Student(String name, int gradeLevel) { this.name = name; this.gradeLevel = gradeLevel; }
void introduce() { System.out.println("Hi, I'm " + name + " and I'm in grade " + gradeLevel + "."); }} Step 2: Create a file named
Program.java and type the following
code:
public class Program{ public static void main(String[] args) { Student s1 = new Student(); // Calls no-arg constructor Student s2 = new Student("Alex", 10); // Calls full constructor
s1.introduce(); s2.introduce(); }}Run the program. Notice how each constructor initializes the object differently.
Modify your Student class to include
a gpa instance variable and use a
full constructor that enforces valid values.
class Student{ String name; int gradeLevel; double gpa;
// No-argument constructor Student() { name = "Unnamed"; gradeLevel = 9; gpa = 0.0; }
// Full constructor with validation Student(String name, int gradeLevel, double gpa) { this.name = name; this.gradeLevel = gradeLevel;
if (gpa < 0.0 || gpa > 4.0) { System.out.println("Invalid GPA! Setting to 0.0..."); this.gpa = 0.0; } else { this.gpa = gpa; } }
void showInfo() { System.out.println(name + " (Grade " + gradeLevel + ") — GPA: " + gpa); }}public class Program{ public static void main(String[] args) {
Student s1 = new Student("Alex", 10, 3.8); Student s2 = new Student("Jordan", 11, 5.2); // invalid GPA triggers fix
s1.showInfo(); s2.showInfo(); }}Run the program and confirm that invalid GPA values are corrected. This pattern appears frequently in AP FRQs involving class design.
Your output should look similar to the following:
Hi, I'm Unnamed and I'm in grade 9.Hi, I'm Alex and I'm in grade 10.
Alex (Grade 10) — GPA: 3.8Invalid GPA! Setting to 0.0...Jordan (Grade 11) — GPA: 0.0Write your answers as comments at the bottom of Main.java.
this
keyword necessary?
Submit your completed Student.java,
Main.java, and reflection responses
to the appropriate dropbox.