Lesson 8 of 10
Constructors & Inheritance
A constructor is a special method that runs when an object is created. It has the same name as the class. Inheritance lets a class (child) extend another class (parent) and reuse its code.
JAVA
// === File: Animal.java ===
public class Animal {
String name;
Animal(String name) {
this.name = name;
}
void speak() {
System.out.println("Some sound");
}
}
// === File: Dog.java ===
public class Dog extends Animal {
Dog(String name) {
super(name);
}
void speak() {
System.out.println("Woof!");
}
}