java · level 2 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A a and gets everything it has.
Dogs and cats are both animals: each has a name and can eat. Write those once, in Animal, then write static class Dog extends Animal. Dog is the subclass, and Animal is its superclass. Dog inherits every field and method, then adds its own.
A subclass constructor must let the superclass fill in its fields first. calls the Animal constructor, and it must be the very first line. After that, the subclass sets up its own extras.
public class Main {
static class Animal {
String name;
Animal(String name) {
this.name = name;
}
String eat() { return name + " is eating."; }
}
static class Dog extends Animal {
Dog(String name) {
super(name);
}
String fetch() { return name + " fetches the ball!"; }
}
public static void main(String[] args) {
Dog rex = new Dog("Rex");
System.out.println(rex.eat());
System.out.println(rex.fetch());
}
} Read extends as is a kind of: a dog is a kind of animal.
guess first
A bike is a kind of vehicle. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
static class Vehicle {
int wheels;
Vehicle(int wheels) {
this.wheels = wheels;
}
}
static class Bike extends Vehicle {
Bike() {
super(2);
}
String ring() { return "Ring ring!"; }
}
public static void main(String[] args) {
Bike bike = new Bike();
System.out.println(bike.wheels + " wheels. " + bike.ring());
}
}
your turn
Your turn. Stock a new kind of item.
Finish line 10 so Book hands the title and price up to the Item constructor. Then choose a title and an author on line 15, and press run.
output
press run to see what happens
fix it
The cat was never built properly. Fix it!
output
press run to see what happens
- Java says
constructor Animal in class Animal cannot be applied to given typeson line 9. - Every cat is built on an animal first, and the Animal constructor needs a name. Cat never hands it one.
- Change line 10 to
super(name);, then press run.
nailed it
you built a family of classes. :D
extendsbuilds a subclass on top of a superclass.- The subclass inherits every field and method.
super(...)comes first in a subclass constructor.
new words in your collection
- extends
- superclass
- subclass
- super
This lesson isn’t saved. A free account remembers every lesson you finish.