AP Computer Science A
2 min read•july 11, 2024
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.
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.
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.