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;
Snack(String n, int c) {
this.name = n;
this.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 {
private String Name;
private String typeOfPet;
private int age;
Pet(String n, String t, int a) {
this.Name = n;
this.typeOfPet = t;
this.age = a;
}
public String getName() {
return this.Name;
}
public String getString() {
return this.typeOfPet;
}
public int getAge() {
return this.age;
}
}
Pet pet = new Pet("fof", "dog", 20);
System.out.println(pet.getName());
System.out.println(pet.getString());
System.out.println(pet.getAge());
fof
dog
20
How can we print out all the information about an instance of an object?
public class SportTester {
public static void main (string[] args) {
Sport volley = new Sport("volleyball", 12);
system.out.println(volley);
}
public String toString(String sportName, int numPlayers) {
return "Sport: " + sportName + ", Players: " + numPlayers;
}
}
| public static void main (string[] args) {
cannot find symbol
symbol: class string
| Sport volley = new Sport("volleyball", 12);
cannot find symbol
symbol: class Sport
| Sport volley = new Sport("volleyball", 12);
cannot find symbol
symbol: class Sport
| system.out.println(volley);
package system does not exist