class Dog extends Animal makes Dog an Animal with everything Animal has, plus what Dog adds. super(name) in the constructor runs the parent's constructor first. A method with the same name and parameters replaces the parent's version (mark it @Override), and super.describe() calls the parent's version from inside the replacement.
A Dog can be stored in an Animal variable, and calling sound() on it runs the Dog version: the object decides, not the variable's type. That is polymorphism, and it is why a list of Animal can hold dogs and cats and make each one speak correctly. instanceof asks which kind an object really is.
class Animal {
String name;
Animal(String name) {
this.name = name;
}
String sound() {
return "...";
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
@Override
String sound() {
return "Woof";
}
}Your task
Using Vehicle from the starter, write class Bicycle extends Vehicle (2 wheels, describe() unchanged) and class Car extends Vehicle (4 wheels) with an extra int doors field set by its constructor Car(String name, int doors), whose describe() returns the parent's description followed by with <doors> doors. Then write static int totalWheels(Vehicle[] fleet) in Main adding up the wheels.
Hint 1
class Bicycle extends Vehicle { Bicycle(String name) { super(name, 2); } }
Hint 2
Car(String name, int doors) { super(name, 4); this.doors = doors; } @Override String describe() { return super.describe() + " with " + doors + " doors"; } totalWheels adds v.wheels for each vehicle.
Show the solution
public class Main {
static int totalWheels(Vehicle[] fleet) {
int total = 0;
for (Vehicle v : fleet) {
total += v.wheels;
}
return total;
}
public static void main(String[] args) {
Vehicle[] fleet = { new Bicycle("Trek"), new Car("Mini", 3) };
System.out.println(fleet[1].describe() + " " + totalWheels(fleet));
}
}
class Vehicle {
String name;
int wheels;
Vehicle(String name, int wheels) {
this.name = name;
this.wheels = wheels;
}
String describe() {
return name + " has " + wheels + " wheels";
}
}
class Bicycle extends Vehicle {
Bicycle(String name) {
super(name, 2);
}
}
class Car extends Vehicle {
int doors;
Car(String name, int doors) {
super(name, 4);
this.doors = doors;
}
@Override
String describe() {
return super.describe() + " with " + doors + " doors";
}
}