🌄 Check out these other AP Computer Science A Resources:


What is a "getter"? 🔍
A "getter" is a public method that allows you to access the value of a private variable that you would otherwise be unable to access. This method is created in the same class that the private variable belongs to, allowing the method to access it and report its value to you. 

The method header for a "getter" that reports the value of a String variable called studentName would be:

public String getStudentName()


The method header for a "getter" that reports the value of a double variable called GPA would be: 

public double getGPA()


Inside the "getter", the code is simply: 

return [variable name];


What is a "setter"? 📝
A "setter" is a public void method that allows you to change the value of a private variable that you would otherwise be unable to access. This method is also created in the same class that the private variable belongs to, allowing the method to access and change its value.

The method header for a "setter" that changes the value of a String variable called studentName would be: 

public void setStudentName (String newName)


The method header for a "setter" that changes the value of a double variable called GPA would be: 

public void setGPA (double newGPA)


Inside the "setter", the code is simply: 

[variable name] = [parameter];


(The parameter is what you pass into the method. In the examples above, the parameter would be "newName" or "newGPA".)


Why do we use these? 🤔
Since private variables cannot be accessed outside of the class they exist in, "getters" and "setters" allow you to indirectly access them so that you can get or change (set) their values.

This is how you would create "getters" and "setters":

public class Dog
{
   private String name;
   
   public String getName()
   {
      return name;
   }

   public void setName (String newName)
   {
      name = newName;
   }

   // There may be instance variables, constructors, and other methods not
   // shown.
}


This is how you would use "getters" and "setters":

Dog testDog = new Dog(); // Creates a Dog called "testDog"

testDog.setName("Snoopy"); // Sets testDog's name to "Snoopy"
System.out.println(testDog.getName()); // Accesses and prints testDog's name


Summary: 🎉✨😎

  • "Getters" and "setters" allow you to indirectly access private variables
  • "Getters" allow you to access the value of a private variable
  • "Setters" allow you to set the value of a private variable
  • "Getters" and "setters" are both public methods
  • A "getter" returns the same type of variable as the one it is accessing 
  • A "setter" is a void method that don't return anything
  • On FRQs, if you need to access a private variable outside of its class, you will need "getters" and "setters"
Did this answer your question?