inheritance Basics
inheritance allows a class to inherit fields and methods from another class. The child class (subclass) extends the parent class (superclass), promoting code reuse and creating a natural hierarchy. This is a foundational concept in enterprise application development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Java experience. Take your time with each section and practice the examples
Understanding inheritance
inheritance creates an 'is-a' relationship. A Dog 'is-a' Animal, a Car 'is-a' Vehicle. The child class inherits all public and protected members from the parent and can add new ones or override existing behavior. Java uses the 'extends' keyword for inheritance.
inheritance in Action
// Parent class (superclass)
class Animal {
String name;
int age;
Animal(String name, int age) {
this.name = name;
this.age = age;
}
void eat() {
System.out.println(name + " is eating.");
}
void sleep() {
System.out.println(name + " is sleeping.");
}
void info() {
System.out.println(name + " (Age: " + age + ")");
}
}
// Child class — inherits Animal's fields & methods
class Dog extends Animal {
String breed;
Dog(String name, int age, String breed) {
super(name, age); // Call parent constructor
this.breed = breed;
}
void bark() {
System.out.println(name + " says: Woof!");
}
void fetch(String item) {
System.out.println(name + " fetches the " + item + "!");
}
}
class Cat extends Animal {
boolean isIndoor;
Cat(String name, int age, boolean isIndoor) {
super(name, age);
this.isIndoor = isIndoor;
}
void purr() {
System.out.println(name + " is purring...");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Dog dog = new Dog("Buddy", 3, "Labrador");
Cat cat = new Cat("Whiskers", 5, true);
// Inherited methods
dog.info();
dog.eat();
dog.bark(); // Dog-specific
dog.fetch("ball");
System.out.println();
cat.info();
cat.sleep();
cat.purr(); // Cat-specific
}
}