java · level 1 · unit 7 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Big programs are small pieces working as a team.
Remember ? A class is a blueprint. Write a small one of your own inside Main, like static class Pet, and list its fields between curly brackets: the boxes every pet gets, such as name and hunger.
new Pet() builds an from the blueprint, and a dot reaches its fields: rex.name = "Rex";. Objects work with everything you know. Hand one to a method, test it with an if, or join its fields into text.
When something goes wrong, you : find the bug, fix it, run again. Every programmer does this every day. Small pieces help, because you can test each one on its own.
public class Main {
static class Pet { String name; int hunger; }
static boolean isHungry(Pet pet) {
return pet.hunger > 5;
}
public static void main(String[] args) {
Pet rex = new Pet();
rex.name = "Rex";
rex.hunger = 8;
System.out.println(rex.name + " is hungry: " + isHungry(rex));
}
} A short class can sit on one line, with a semicolon after each field.
guess first
Two pets, one blueprint. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
static class Pet { String name; int hunger; }
public static void main(String[] args) {
Pet rex = new Pet();
Pet tiddles = new Pet();
rex.hunger = 8;
tiddles.hunger = 2;
System.out.println(rex.hunger);
}
}
your turn
Your turn. Make a hungry pet.
Give your pet a name on line 5 and a hunger level on line 6, as a whole number. Make it bigger than 5, then press run.
output
press run to see what happens
fix it
Rex never got built. Debug it!
output
press run to see what happens
- Java says
variable rex might not have been initialized. Look at line 4. - Line 4 makes a box for a pet, but never builds a pet to put in it.
- Change line 4 to
Pet rex = new Pet();, then press run.
nailed it
you put all the pieces together. :D
- A class is a blueprint.
newbuilds an object from it. - Each object keeps its own fields, reached with a dot.
- To debug, find the bug, fix it, then run again.
new words in your collection
- class
- object
- field
- debug
This lesson isn’t saved. A free account remembers every lesson you finish.