Learn Java · lesson 39 of 61 · about 8 minutes
Methods and this
Run the snack bar: give objects behaviour with instance methods, and print them nicely with toString.
What you'll learn
- Write instance methods
- Use this inside methods
- Override toString
The snack bar
The snack bar sells popcorn at $4.50 and lemonade at $3.00, and each snack keeps count of how many it has sold. A Snack object knows its own name and price, sell(n) adds to its count (ignoring numbers that aren't above 0), and takings() works out what it has made. Its toString() decides what printing it shows, so System.out.println(popcornTub) prints popcorn x2 ($9.00).
Behaviour
Methods without static belong to each object. They can read and change that object's fields, and you call them on an object: pet.feed(2).
A method that changes its object
class Torch {
int battery = 3;
void use() {
battery--;
}
}
public class Main {
public static void main(String[] args) {
Torch t = new Torch();
t.use();
t.use();
System.out.println(t.battery);
}
}
Output
1toString
Override toString() to decide what printing an object shows. Without it, you get something like Pet@1b6d3586.
A pet with methods
class Pet {
private final String name;
private int hunger = 5;
Pet(String name) {
this.name = name;
}
void feed(int amount) {
hunger = Math.max(0, hunger - amount);
}
boolean isHungry() {
return hunger > 2;
}
@Override
public String toString() {
return name + " (hunger " + hunger + ")";
}
}
public class Main {
public static void main(String[] args) {
Pet p = new Pet("Phoebe");
System.out.println(p + " " + p.isHungry());
p.feed(4);
System.out.println(p + " " + p.isHungry());
}
}Output
Phoebe (hunger 5) true
Phoebe (hunger 1) falseNow try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.