7.2 Inheritance
In Java, Inheritance is a core concept of Object-Oriented Programming that allows a new class to be based on an existing class, absorbing its properties and behaviors.
Just as a child inherits traits from their parents in the real world, a subordinate (child) class in Java inherits fields and methods from a superordinate (parent) class. This mechanism greatly reduces redundant code and enhances maintainability.
1. Characteristics of Inheritance and the extends Keyword
To implement inheritance in Java, use the extends keyword followed by the name of the parent class when defining the child class.
class ParentClass {
// Fields and methods of the parent
}
class ChildClass extends ParentClass {
// Unique fields and methods (can also use the parent's)
}
- Parent Class: The class that provides the inheritance. Also known as a Super Class or Base Class.
- Child Class: The class that inherits. Also known as a Sub Class or Derived Class.
Example: Basic Inheritance
Let's look at a common example: creating 'Characters' for a game.
// Parent Class: Common properties for all characters
class Character {
String name;
int hp;
void walk() {
System.out.println(name + " is walking. (tap tap)");
}
}
// Child Class: A Warrior that inherits from Character
class Warrior extends Character {
int rage; // Unique field for Warrior
void attack() {
System.out.println("Warrior " + name + " attacks with a sword! Slash!");
}
}
// Child Class: A Magician that inherits from Character
class Magician extends Character {
int mp; // Unique field for Magician
void castSpell() {
System.out.println("Magician " + name + " casts a fireball! Boom!");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Warrior w = new Warrior();
w.name = "DarkKnight"; // Inherited field
w.hp = 1000; // Inherited field
w.rage = 100; // Own field
w.walk(); // Call to inherited method
w.attack(); // Call to own method
Magician m = new Magician();
m.name = "Gandalf";
m.hp = 500;
m.mp = 1500;
m.walk();
m.castSpell();
}
}
In the example above, the Warrior class doesn't have name or walk() explicitly defined within it, but because of extends Character, it can use them as if they were its own! This makes the code very concise. If later you decide "Every character needs a run() method!", you only have to add it to the Character class, demonstrating high efficiency.
2. Important Rules of Inheritance in Java
- Single Inheritance Only:
- Unlike C++, Java does not support multiple inheritance for classes. A child class can only have one direct parent class.
- You cannot write
class Child extends Father, Mother { }. This prevents ambiguity and the "Diamond Problem."
- The Supreme Ancestor:
ObjectClass:- Every class you create in Java automatically inherits from
java.lang.Object, the absolute root of the Java class hierarchy, even if you don't explicitly writeextends Object. - Methods you commonly use, such as
toString()andequals(), are actually inherited from thisObjectclass.
- Every class you create in Java automatically inherits from
- Constructors are NOT Inherited:
- While a parent's member fields and methods are inherited, constructors and initialization blocks are not. However, when a child class constructor is called, the parent class's no-argument constructor is implicitly invoked first to initialize the inherited members.
3. Referring to the Parent with super and super()
In a previous chapter, we learned about the this keyword used to refer to the current object. Similarly, we use super to refer to the parent class from within a child class.
super: A reference variable used to access a parent's fields or methods that might have been hidden or overridden by the child.super(): A method call to invoke the parent class's constructor.
Example of super() Constructor Call
When a child object is instantiated, the parent portion must also be created in memory. To facilitate this, Java mandates that the parent's constructor (super()) must be called as the very first statement in the child's constructor. If you don't write it, the compiler automatically inserts super(); for you.
class Parent {
int x;
Parent() {
System.out.println("Parent default constructor called!");
this.x = 10;
}
}
class Child extends Parent {
int y;
Child() {
// The compiler automatically inserts super(); here.
System.out.println("Child default constructor called!");
this.y = 20;
}
}
public class SuperExample {
public static void main(String[] args) {
Child c = new Child();
}
}
[Execution Result]
Parent default constructor called!
Child default constructor called!
Inheritance in Java eliminates the drudgery of copy-pasting code and centrally manages shared logic, making it an essential technique. In the next chapter (7.3), we will explore how a child can customize (Override) inherited methods and the true power of Polymorphism.