Unit 5 Classes - Accessor Methods
What is an accessor method?
- Allow safe access to instance variables
- Prevents access to variables from outside
- AKA “get methods” or “getters”
- If another class or a function needs access to the variable, you use an accessor method
Example:
public class snack {
private String name;
private int calories;
public Snack() {
name "";
calories = 0;
}
public Snack (string n, int c) {
name = n;
calories = c;
}
public String getName(){
return Name;
}
public int getCalories() {
return calories;
}
}
Private Instance Variables:
private String name;
private int calories;
Default Constructors
public Snack() {
name "";
calories = 0;
}
Overload Constructor
public Snack (string n, int c) {
name = n;
calories = c;
}
Accessor Methods
` public String getName(){ return Name; }`
public int getCalories() {
return calories;
}
- Return command reciprocate a copy of the instance variable
Requirements
- Accessor Methods must be public
- Return type must match the variable type
- int = int
- string = string
- etc
- REMEMBER PRINTING A VALUE IS NOT THE SAME AS RETURNING
- Name appropriately
- Often is
getNameOfVariable
- Often is
- No parameters
Notice how the methods from the example match: public String getName(){
and public int getCalories()
Popcorn Hack #1:
Below is a constructor of a class, write the acccessor methods for all instance variables.
public class Pet {
// Instance variables
private String name;
private String typeOfPet;
private int age;
public Pet(String name, String typeOfPet, int age) {
this.name = name;
this.typeOfPet = typeOfPet;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getTypeOfPet() {
return typeOfPet;
}
public void displayPetDetails() {
System.out.println("Pet Name: " + getName());
System.out.println("Pet Type: " + getTypeOfPet());
System.out.println("Pet Age: " + getAge());
}
}
Pet myPet = new Pet("Buddy", "Dog", 5);
myPet.displayPetDetails();
Pet Name: Buddy
Pet Type: Dog
Pet Age: 5
How can we print out all the information about an instance of an object?
public class Sport {
private String sportName;
private int numPlayers;
public Sport(String sportName, int numPlayers) {
this.sportName = sportName;
this.numPlayers = numPlayers;
}
@Override
public String toString() {
return "Sport: " + sportName + ", Players: " + numPlayers;
}
}
public class SportTester {
public static void main(String[] args) {
Sport volley = new Sport("Volleyball", 12);
System.out.println(volley);
}
}
SportTester.main(null);
Sport: Volleyball, Players: 12