Methods that return a value
In module 17 the methods of your classes did something: they printed, or they changed the object's instance variables. They were all void. An object's method can also return a value, just like the methods of module 11. This basket counts its fruit:
public class Main {
public static void main(String[] args) {
Basket basket = new Basket();
System.out.println(basket.isEmpty());
basket.addApples(3);
basket.addPears(2);
int fruit = basket.total();
System.out.println("Fruit in the basket: " + fruit);
System.out.println(basket.isEmpty());
}
}public class Basket {
private int apples;
private int pears;
public Basket() {
this.apples = 0;
this.pears = 0;
}
public void addApples(int count) {
this.apples = this.apples + count;
}
public void addPears(int count) {
this.pears = this.pears + count;
}
public int total() {
return this.apples + this.pears;
}
public boolean isEmpty() {
return this.apples + this.pears == 0;
}
}true
Fruit in the basket: 5
falsepublic int total()returns anint: the apples and pears of this basket added up. There's nostaticin the header, because the method belongs to an object and works with that object's own variables.- In
main, the callbasket.total()stands for the value it returns. Heremainstores it infruit, but the call can go anywhere a value can: in a print line, a calculation or a comparison. isEmpty()returns aboolean, so its call works as a condition on its own:if (basket.isEmpty()) { ... }. A method that answers a yes-or-no question usually has a name that starts withisorhas, such asisEmptyorhasRoom.
You've used methods like these on lists and strings: list.size() returns how many values a list has, and word.isEmpty() tells whether a string is empty. Now your own classes can have them too.
Why return the value instead of printing it? For the same reason as in module 11: the caller decides what to do with it. main can compare the totals of two baskets, add them up, or print them in its own words.