java · level 2 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An is a skill every object carries.
So far your methods have been static: they belong to Main, and you hand them everything they need. Leave out static inside your own class, and you get an instance method. Every object carries it, and it can use that object's fields directly.
Call it with the object, a dot and the name: rex.feed(). Inside, hunger means the hunger of rex. Call tiddles.feed(), and the same method works on the hunger of tiddles instead.
main is static, so it has no object of its own. It always names the object before the dot.
public class Main {
static class Pet {
String name;
int hunger;
Pet(String name, int hunger) {
this.name = name;
this.hunger = hunger;
}
void feed() { hunger = hunger - 3; }
boolean isHungry() { return hunger > 5; }
}
public static void main(String[] args) {
Pet rex = new Pet("Rex", 8);
System.out.println(rex.name + " hungry: " + rex.isHungry());
rex.feed();
System.out.println(rex.name + " hungry: " + rex.isHungry());
}
} Inside an instance method, hunger and this.hunger mean the same field.
guess first
Two piggy banks, one method. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
static class PiggyBank {
int pence;
PiggyBank(int pence) {
this.pence = pence;
}
void save(int amount) { pence = pence + amount; }
}
public static void main(String[] args) {
PiggyBank mine = new PiggyBank(100);
PiggyBank yours = new PiggyBank(50);
mine.save(20);
yours.save(5);
mine.save(30);
System.out.println(mine.pence + " and " + yours.pence);
}
}
your turn
Your turn. Teach the robot to talk.
Finish greet on line 7 so it uses the robot's own name. Then name your robot on line 10, and press run.
output
press run to see what happens
fix it
Which dog should bark? Fix it!
output
press run to see what happens
- Java says
non-static method bark() cannot be referenced from a static contexton line 11. barkbelongs to each dog, not to the class. Which dog should bark? Mind the capital letter.- Change
Dog.bark()todog.bark()on line 11, then press run.
nailed it
your objects have skills of their own. :D
- An instance method has no
staticand belongs to each object. - Call it on an object, like
rex.feed(). - Inside, a field name means that object's own field.
new words in your collection
- instance method
This lesson isn’t saved. A free account remembers every lesson you finish.