πŸ“š

Β >Β 

πŸ’»Β 

Β >Β 

βš™οΈ

5.9 This Keyword

5 min readβ€’june 18, 2024

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang

Introduction to This

In the last topic, we posed this scenario:

If there is a local variable (usually a parameter) and a global variable (usually an instance variable) in the same method with the same name, the local variable takes precedence. However, it is convention for our constructor and mutator parameters to have the same names as our instance variables!

Now, we will come up with a way to fix this. This will also give us a way to efficiently overload constructors as well. Once we learn about this, we can finish our classes once and for all! So what is this mysterious strategy?

The answer lies in theΒ this keyword. The this keyword is a keyword that essentially refers to the object that is calling the method or the object that the constructor is trying to make. There are three ways to use this:Β 

  1. To refer to an instance variable This will solve the problem of having duplicate variable names. To distinguish the instance and local variables, we useΒ this.variableName for the instance variable and simplyΒ variableName for the local variable.

  2. As a parameter Sometimes, we can also use the object as a parameter in its own method call to use itself in the method by usingΒ objectName.methodName(this).

  3. As a constructor or method call This will allow us to overload our constructors effectively. Inside the overloaded constructors, we can make a call to the full constructor usingΒ this() where the parameters include the default values as well. We can also use this way as a method call to call a method inside a method call as well usingΒ this.methodName().

Finishing Our Classes

With this last bit of new information, it's time to finish our classes! It's time to add our overloaded constructors and also a few final methods as well! As before, all new additions will be bolded.

/** Represents an assignment that a student will complete
*/
public class Assignment {
  private boolean correctAnswer; // represents the answer to an assignment, either T/F

  /** Makes a new assignment with one True/False question and sets the correct answer
  */
  public Assignment(boolean correctAnswer) {
    this.correctAnswer = correctAnswer;
  }

  **/** Makes a new assignment with a randomized answer
  */
  public Assignment() {
    double number = Math.random();
    // Makes a random double and sets answer to false if less than 0.5, otherwise true
    if number < 0.5 {
      this(false);
    } else {
      this(true);
    }
  }**
  
  /** Prints details about the assignment
  */
  @Override
  public String toString() {
    return "This is an assignment with correct answer " + answer;
  }

  /** Grades an assignment, returns true if correct, false if incorrect
  */
  public boolean gradeAssignment(boolean studentAnswer) {
    return studentAnswer == correctAnswer;
  }
}

/** Represents a high school student
*/
public class Student {
  private int gradeLevel; // a grade between 9-12
  private String name; // the students name in the form "FirstName LastName"
  private int age; // the student's age, must be positive
  private Assignment assignment; // the current assignment the student is working on
  private int assignmentsComplete; // numbers of assignments completed
  private int correctAssignments; // number of correct assignments

  private static final int A_BOUNDARY = 0.9;
  private static final int B_BOUNDARY = 0.8;
  private static final int C_BOUNDARY = 0.7;
  private static final int D_BOUNDARY = 0.6;
  private static String school = "The Fiveable School";

  /** Makes a new student with grade gradeLev, name fullName, and age ageNum
  */
  public Student(int gradeLevel, String namelName, int age) {
    this.gradeLevel = gradeLevel;
    this.name = name;
    this.age = age;
    assignment = null; // There is no active assignment at the moment
    assignmentsComplete = 0; // no assignments complete yet
    correctAssignments = 0;
  }

  /** Returns the student's grade level
  */
  public int getGradeLevel() {
    return gradeLevel;
  }
  
  /** Returns the student's name
  */
  public String getName() {
    return name;
  }
  
  /** Returns the current assignment the student is working on
  */
  public Assignment returnCurrentAssignment() {
    return assignment;
  }

  /** Prints details about the student
  */
  @Override
  public String toString() {
    return name + ", a " + gradeLevel + "th grade high school student has an average grade of " + averageGrade + ".";
  }

  /** Changes the student's name
  */
  public void setName(String fullName) {
    name = fullName;
  }

  /** Changes the student's grade level
  */
  public void setGradeLevel(int gradeLev) {
    gradeLevel = gradeLev;
  }
  
  **/** Gives the student a new assignment
  */
  public void newAssignment() {
    assignment = new Assignment();
  }**

  /** Submits an assignment
  */
  public void submitAssignment() {
    boolean grade = assignment.gradeAssignment();
    assignmentsComplete++;
    if grade {
      correctAssignments++
    }
  }  

  /** Calculates the student's grade as a decimal 
  */
  public double getGradeDecimal() {
    return (double) correctAssignments / assignmentsComplete;
  }

Β Β **/** Gets the student's letter grade
  */
  public String getLetterGrade() {
    double grade = this.getGradeDecimal(); // get the decimal grade
    // compares the grade to the grade boundaries
    if grade >= A_BOUNDARY {
      return "A";
    } else if grade >= B_BOUNDARY {
      return "B";
    } else if grade >= C_BOUNDARY {
      return "C";
    } else if grade >= D_BOUNDARY {
      return "D";
    } else {
      return "F";
    }
  }**

  /** Changes the school that the students go to
  */
  public static void setSchool(String schoolName) {
    school = schoolName;
  }
}

<< Hide Menu

πŸ“š

Β >Β 

πŸ’»Β 

Β >Β 

βš™οΈ

5.9 This Keyword

5 min readβ€’june 18, 2024

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang

Introduction to This

In the last topic, we posed this scenario:

If there is a local variable (usually a parameter) and a global variable (usually an instance variable) in the same method with the same name, the local variable takes precedence. However, it is convention for our constructor and mutator parameters to have the same names as our instance variables!

Now, we will come up with a way to fix this. This will also give us a way to efficiently overload constructors as well. Once we learn about this, we can finish our classes once and for all! So what is this mysterious strategy?

The answer lies in theΒ this keyword. The this keyword is a keyword that essentially refers to the object that is calling the method or the object that the constructor is trying to make. There are three ways to use this:Β 

  1. To refer to an instance variable This will solve the problem of having duplicate variable names. To distinguish the instance and local variables, we useΒ this.variableName for the instance variable and simplyΒ variableName for the local variable.

  2. As a parameter Sometimes, we can also use the object as a parameter in its own method call to use itself in the method by usingΒ objectName.methodName(this).

  3. As a constructor or method call This will allow us to overload our constructors effectively. Inside the overloaded constructors, we can make a call to the full constructor usingΒ this() where the parameters include the default values as well. We can also use this way as a method call to call a method inside a method call as well usingΒ this.methodName().

Finishing Our Classes

With this last bit of new information, it's time to finish our classes! It's time to add our overloaded constructors and also a few final methods as well! As before, all new additions will be bolded.

/** Represents an assignment that a student will complete
*/
public class Assignment {
  private boolean correctAnswer; // represents the answer to an assignment, either T/F

  /** Makes a new assignment with one True/False question and sets the correct answer
  */
  public Assignment(boolean correctAnswer) {
    this.correctAnswer = correctAnswer;
  }

  **/** Makes a new assignment with a randomized answer
  */
  public Assignment() {
    double number = Math.random();
    // Makes a random double and sets answer to false if less than 0.5, otherwise true
    if number < 0.5 {
      this(false);
    } else {
      this(true);
    }
  }**
  
  /** Prints details about the assignment
  */
  @Override
  public String toString() {
    return "This is an assignment with correct answer " + answer;
  }

  /** Grades an assignment, returns true if correct, false if incorrect
  */
  public boolean gradeAssignment(boolean studentAnswer) {
    return studentAnswer == correctAnswer;
  }
}

/** Represents a high school student
*/
public class Student {
  private int gradeLevel; // a grade between 9-12
  private String name; // the students name in the form "FirstName LastName"
  private int age; // the student's age, must be positive
  private Assignment assignment; // the current assignment the student is working on
  private int assignmentsComplete; // numbers of assignments completed
  private int correctAssignments; // number of correct assignments

  private static final int A_BOUNDARY = 0.9;
  private static final int B_BOUNDARY = 0.8;
  private static final int C_BOUNDARY = 0.7;
  private static final int D_BOUNDARY = 0.6;
  private static String school = "The Fiveable School";

  /** Makes a new student with grade gradeLev, name fullName, and age ageNum
  */
  public Student(int gradeLevel, String namelName, int age) {
    this.gradeLevel = gradeLevel;
    this.name = name;
    this.age = age;
    assignment = null; // There is no active assignment at the moment
    assignmentsComplete = 0; // no assignments complete yet
    correctAssignments = 0;
  }

  /** Returns the student's grade level
  */
  public int getGradeLevel() {
    return gradeLevel;
  }
  
  /** Returns the student's name
  */
  public String getName() {
    return name;
  }
  
  /** Returns the current assignment the student is working on
  */
  public Assignment returnCurrentAssignment() {
    return assignment;
  }

  /** Prints details about the student
  */
  @Override
  public String toString() {
    return name + ", a " + gradeLevel + "th grade high school student has an average grade of " + averageGrade + ".";
  }

  /** Changes the student's name
  */
  public void setName(String fullName) {
    name = fullName;
  }

  /** Changes the student's grade level
  */
  public void setGradeLevel(int gradeLev) {
    gradeLevel = gradeLev;
  }
  
  **/** Gives the student a new assignment
  */
  public void newAssignment() {
    assignment = new Assignment();
  }**

  /** Submits an assignment
  */
  public void submitAssignment() {
    boolean grade = assignment.gradeAssignment();
    assignmentsComplete++;
    if grade {
      correctAssignments++
    }
  }  

  /** Calculates the student's grade as a decimal 
  */
  public double getGradeDecimal() {
    return (double) correctAssignments / assignmentsComplete;
  }

Β Β **/** Gets the student's letter grade
  */
  public String getLetterGrade() {
    double grade = this.getGradeDecimal(); // get the decimal grade
    // compares the grade to the grade boundaries
    if grade >= A_BOUNDARY {
      return "A";
    } else if grade >= B_BOUNDARY {
      return "B";
    } else if grade >= C_BOUNDARY {
      return "C";
    } else if grade >= D_BOUNDARY {
      return "D";
    } else {
      return "F";
    }
  }**

  /** Changes the school that the students go to
  */
  public static void setSchool(String schoolName) {
    school = schoolName;
  }
}