🌄 Check out these other AP Computer Science A Resource

  • Attend AP CS A live streams every week with Fiveable+ 👉 Join here

What does "private" mean? 🤔
When a variable is "private", it means that the value of the variable can only be accessed from inside the class the variable is declared in. You cannot directly access or change the value of the value from outside the class. A private method is the same, it can only be called from inside the class the method is written in.

Example: 🔍

public class Student
{
   private String name;

   public Student (String newName)
   {
      name = newName;
   }

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


This code will not work: 🚫😱

public class Athlete extends Student
{
   public void printName ()
   {
      System.out.println(name); // THIS WILL NOT WORK
   }

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


The "System.out.println(name)" would only work if name was a public variable. Since name is a private variable, the code in the Athlete class does not inherit name and cannot access the value of name

So how can you print name or change what's stored in it? You'll have to use getters and setters (the "setName(...)" and "getName()" methods in the Student class). For more information on using these, visit the article on getters and setters. 

Summary: 🎉✨😎

  • A "private" variable or method cannot be accessed from outside its class
  • On FRQs, you'll need to use getters and setters to access the values of private variables
Did this answer your question?