Private Variables

2 min readjuly 11, 2024

Milo Chang

Milo Chang


AP Computer Science A 💻

130 resources
See Units

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
Browse Study Guides By Unit
Unit 1 – Primitive Types
📱Unit 2 – Using Objects
🖥Unit 3 – Boolean Expressions & if Statements
🕹Unit 4 – Iteration
⚙️Unit 5 – Writing Classes
⌚️Unit 6 – Array
💾Unit 7 – ArrayList
💻Unit 8 – 2D Array
🖲Unit 9 – Inheritance
🖱Unit 10 – Recursion
🧐Exam Skills

Fiveable
Fiveable
Home
Stay Connected

© 2024 Fiveable Inc. All rights reserved.


© 2024 Fiveable Inc. All rights reserved.