AP Computer Science A

Private Variables

2 min readjuly 11, 2024

Milo Chang

Milo Chang

Milo Chang

Milo Chang

In Java, you may notice keywords in front of variables, especially when looking at object-oriented programming. For example, private is one of the most important keywords, especially in object-oriented programming and within class structures. 

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
© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.
Glossary
Glossary