Java Inheritance
By Connor Young
Definition:
Inheritance: Refers to classes that can be derived from other classes, thereby inheriting fields and methods from those classes. This includes the use of subclasses and superclasses.
- The classes Car and Truck are subclasses of the class Vehicle
- The class Vehicle is the superclass of the classes Car and Truck
- These classes are all related through inheritance
Example:
Animal.java:
public class Animal {
public Animal() {
System.out.println("A new animal has been created!");
}
public void sleep() {
System.out.println("An animal sleeps...");
}
public void eat() {
System.out.println("An animal eats...");
}
}
Bird.java:
public class Bird extends Animal {
public Bird() {
super();
System.out.println("A new bird has been created!");
}
@Override
public void sleep() {
System.out.println("A bird sleeps...");
}
@Override
public void eat() {
System.out.println("A bird eats...");
}
}
- Both classes Animal and Bird above are related to each other by inheritance
- The class Animal is the superclass of the class Bird, and the class Bird is a subclass of the class Animal
Important Facts:
- You can have an 'infinite' amount of subclasses
- Each subclass can only extend to one superclass
- Inheritance allows programmers to re-use code that they have already written
- Subclasses can become superclasses over its own subclasses