Subjects

Subjects

More

This Keyword

Learn with content from all year groups and subjects, created by the best students.

The "this" Keyword: AP Computer Science A Study Guide



Introduction

Hey there, future coding wizards! Ready to dive into one of the coolest parts of Java? 🧙‍♂️ Get comfy, because today we're talking about the "this" keyword. Imagine "this" as the ultimate hype person for your objects. It always knows which object it's dealing with—no mix-ups, no confusion. But why do we even need "this"? Let's find out.



Introduction to "this"

Picture this: You're a method, and you've got a local variable and an instance variable with the exact same name. Talk about awkward encounters! After a few panic attacks, Java realized it needed some clarity. Enter the "this" keyword, the hero we didn't know we needed.

The "this" keyword is essentially a backstage pass to the current object calling the method or the constructor. Because even Java knows that clarity is key, especially when variables start acting like identical twins at a party. Let's break down the three main ways you can use "this" in your code:

  1. Referring to Instance Variables: Imagine you're trying to tell apart two identical twins. You'd look for something that sets them apart, right? "This" does just that for your variables. To refer to an instance variable when there's a naming collision with a local variable (like in constructors or setters), use this.variableName.

  2. As a Method Parameter: Picture this: you're being very self-centered (in a good way!). You want to pass yourself (the object) into a method to make things clearer. You can do this by using objectName.methodName(this).

  3. Constructor or Method Call: Overloaded constructors are like Lego sets with interchangeable pieces. To call one constructor from another (to avoid redundant code), you can use this(). It's like calling your sibling to borrow their homework when you're too lazy to do yours.



The Great "this" Adventure

Enough with the theory. Let’s see "this" in action by adding method and constructor overloading magic to our classes. Here’s a code peek into how you should be handling “this” like a pro.

/** 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.correctAnswer = false;
    } else {
      this.correctAnswer = true;
    }
  }
  
  /** Prints details about the assignment */
  @Override
  public String toString() {
    return "This is an assignment with correct answer: " + correctAnswer;
  }

  /** 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 student's 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; // number 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 name, 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 completed yet
    correctAssignments = 0;
  }

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

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

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

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

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

  /** Calculates the student's grade as a decimal */
  public double getGradeDecimal() {
    if (assignmentsComplete == 0) {
      return 0;
    }
    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;
  }
}


Key Terms to Review

  • @Override: Ensures a method in a subclass is overriding a method in the superclass. It's like a big neon sign blinking, "Yes, you got it right!"
  • Constructor: A special method used to initialize objects of a class, doing the groundwork for object creation.
  • getGradeDecimal Method: Returns the grade as a decimal. It's like a score converter from numbers to a more Java-friendly decimal.
  • getLetterGrade method: Converts numerical grades into letter grades, making those numbers socially acceptable.
  • gradeAssignment method: Grades a student's assignment, determining pass or fail, like a strict schoolteacher.
  • If statement: Executes a block of code only if a specific condition is true, like a conditional friendship.
  • Method Call: Invokes a method in your code, like summoning a genie (minus the wishes).
  • Mutator (Setter): Allows us to change the value of an instance variable after the object is created, like a makeover for the variable.
  • Overload Constructors: Different constructors in a class, each with unique parameters. Think of it as a potluck with diverse dishes.
  • Private modifier: Restricts access to members within a class. It’s like a VIP area in the club—no trespassing.
  • returnCurrentAssignment method: Fetches the current assignment for a student, keeping tabs on their workload.
  • Static final modifier: Declares constants, signifying unchanging, reliable values you can always count on.
  • submitAssignment method: Allows students to submit their homework, finally ending their coffee-fueled all-nighters.
  • this keyword: Refers to the current object, ensuring there's no confusion about who’s who.
  • toString method: Converts an object into its string representation, helping objects speak in text.


Fun Fact

Did you know that without constructors, creating objects would be like attempting to assemble IKEA furniture without instructions? Constructor methods give us the ultimate guide to initializing our objects properly.



Conclusion

Armed with the power of the "this" keyword, you're ready to play in the big leagues of Java programming. It's the secret sauce that keeps your code clear and organized, just like a neat freak's dream closet. So, go forth and conquer those AP CSA challenges with confidence. And remember, in Java (and in life), sometimes you just need to get a little selfish... with "this"! 🚀

Knowunity is the # 1 ranked education app in five European countries

Knowunity was a featured story by Apple and has consistently topped the app store charts within the education category in Germany, Italy, Poland, Switzerland and United Kingdom. Join Knowunity today and help millions of students around the world.

Ranked #1 Education App

Download in

Google Play

Download in

App Store

Knowunity is the # 1 ranked education app in five European countries

4.9+

Average App Rating

15 M

Students use Knowunity

#1

In Education App Charts in 12 Countries

950 K+

Students uploaded study notes

Still not sure? Look at what your fellow peers are saying...

iOS User

I love this app so much [...] I recommend Knowunity to everyone!!! I went from a C to an A with it :D

Stefan S, iOS User

The application is very simple and well designed. So far I have found what I was looking for :D

SuSSan, iOS User

Love this App ❤️, I use it basically all the time whenever I'm studying

Can't find what you're looking for? Explore other subjects.