A Bike is a Vehicle. Reuse the parent's fields and methods, and call its constructor with super(...).
Java · beginner · 8 min · 13 steps · free
class Vehicle {
int wheels;
Vehicle(int wheels) {
this.wheels = wheels;
}
String describe() {
return "a vehicle with " + wheels + " wheels";
}
}
class Bike extends Vehicle {
boolean hasBell;
Bike() {
super(2);
hasBell = true;
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Bike bike = new Bike();
String text = bike.describe();
System.out.println(text + ", bell: " + bike.hasBell);
}
}super(2) runs Vehicle's constructor first, setting wheels to 2.Object) runs first.wheels in the Bike object changes from 0 to 2.Vehicle() has finished, so its variables are gone.Bike() has finished, so its variables are gone.describe() has finished, so its variables are gone.text.a vehicle with 2 wheels, bell: true.Answer: No: only one. Java allows single class inheritance (but many interfaces).
Answer: Vehicle's. The parent part is built first.
← Encapsulation: private Fields and Methods · Polymorphism and Overriding →