πŸ“š

Β >Β 

πŸ’»Β 

Β >Β 

✏️

Private Variables

2 min readβ€’december 21, 2021

Milo Chang

Milo Chang

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 Reviews