Let’s start with a real-life example: Why do both cats and dogs belong to the category “animal” instead of defining two completely separate sets of code? This is where inheritance comes in! The core idea of inheritance is that a subclass can reuse the attributes and methods of its superclass while extending its own functionality. Imagine that both cats and dogs are animals (the superclass), and they inherently inherit common traits from “animals” (like breathing and eating). However, each subclass also has unique behaviors (e.g., cats catch mice, dogs guard houses). This relationship of “what I have, you have too, and what I have, you can do even better” is exactly what inheritance solves.
1. Basic Syntax of Inheritance: Subclass extends Superclass¶
To implement inheritance, you first define a superclass, then use the extends keyword to define a subclass that inherits from the superclass.
Example:
// Superclass: Animal (defines common characteristics)
class Animal {
// Superclass attributes (member variables): All animals have a name and age
String name;
int age;
// Superclass methods (member methods): Common behaviors of animals
public void eat() {
System.out.println(name + " is eating");
}
public void sleep() {
System.out.println(name + " is sleeping");
}
}
// Subclass: Cat (inherits from Animal)
class Cat extends Animal {
// Subclass can add its own attributes/methods (unique behaviors of cats)
String color; // Cat's color
public void catchMouse() {
System.out.println(name + " is catching a mouse!");
}
}
Key Points:¶
- Superclass (Animal): Defines shared characteristics (attributes and methods).
- Subclass (Cat): Uses the
extendskeyword to inherit all non-privateattributes and methods from the superclass, and can add its own functionality.
2. What Can a Subclass Inherit? What Cannot?¶
After inheriting from the superclass, a subclass automatically gains:
- The superclass’s non-private attributes (member variables).
- The superclass’s non-private methods (member methods).
Note: Attributes/methods modified with private in the superclass cannot be directly accessed by the subclass! If access is needed, it must be done through the superclass’s public or protected methods (e.g., getters/setters).
class Animal {
private String name; // Private attribute, cannot be directly accessed by subclasses
// Superclass provides public methods to access private attributes
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Cat extends Animal {
public void test() {
// Directly accessing the superclass's name will cause an error!
// System.out.println(name); // Error!
System.out.println(getName()); // Correct: Access via superclass's public method
}
}
3. Core of Inheritance: “is-a” Relationship¶
Inheritance is not arbitrary! The subclass and superclass must have an “is-a” relationship (the subclass is a type of the superclass).
- ✅ Correct: A cat is an animal →
Cat extends Animal(a cat “is” an animal). - ❌ Incorrect: If the relationship is “a cat has a claw” (a “has-a” relationship), composition should be used instead of inheritance.
Example:
// Correct: A student is a type of person (is-a)
class Student extends Person {}
// Incorrect: A wheel is not a type of vehicle (has-a relationship)
// class Wheel extends Vehicle {}
4. Method Overriding (Override): Subclass “Personalizes” Superclass Methods¶
A subclass can override a superclass method, modifying its implementation logic while keeping the method signature (return type, parameter list) unchanged.
Example: The superclass Animal has a makeSound() method, and subclasses Cat and Dog override this method to produce different sounds.
class Animal {
public void makeSound() {
System.out.println("An animal makes a sound");
}
}
class Cat extends Animal {
// Override the superclass's makeSound method
@Override // Annotation: tells the compiler this is method overriding (optional but recommended)
public void makeSound() {
System.out.println("Meow~");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
Test:¶
Cat myCat = new Cat();
myCat.makeSound(); // Output: Meow~
Dog myDog = new Dog();
myDog.makeSound(); // Output: Woof!
5. super Keyword: Calling the Superclass’s “Me”¶
The super keyword in Java is used to call the superclass’s attributes, methods, or constructor.
5.1 Calling Superclass Attributes/Methods¶
If the subclass and superclass have attributes/methods with the same name, use super to explicitly specify the superclass:
class Animal {
String name = "Animal";
public void info() {
System.out.println("I am " + name);
}
}
class Cat extends Animal {
String name = "Cat"; // Subclass's attribute with the same name
public void showInfo() {
System.out.println("Subclass name: " + name); // Call subclass attribute
System.out.println("Superclass name: " + super.name); // Call superclass attribute
}
}
5.2 Calling the Superclass’s Constructor¶
In a subclass constructor, super() must be placed first to call the superclass’s constructor:
class Animal {
String name;
public Animal(String name) { // Superclass parameterized constructor
this.name = name;
}
}
class Cat extends Animal {
public Cat(String name) {
super(name); // Must call superclass constructor first
this.name = name;
}
}
6. Advantages and Considerations of Inheritance¶
Advantages:¶
- Code Reusability: The superclass defines common traits, and subclasses inherit them directly, avoiding repeated code writing.
- Extensibility: Subclasses can add new functionality on top of the superclass (e.g.,
Catadds thecatchMouse()method). - Clear Structure: Inheritance forms a class hierarchy (e.g., Animal → Cat → Chinese田园 cat).
Considerations:¶
- Single Inheritance: Java classes can only single-inherit (a subclass can only have one direct superclass), but multiple levels of inheritance are supported (subclass of a subclass).
- Private Members Cannot Be Directly Accessed: Superclass
privateattributes/methods must be accessed throughpublicmethods. - Method Overriding Rules: The return type and parameter list of a subclass method must be exactly the same as the superclass (covariant return types are an exception, e.g., superclass returns Object, subclass returns String).
Summary¶
Inheritance is a core feature of Java’s object-oriented programming, implemented via the extends keyword to allow subclasses to inherit attributes and methods from superclasses. Key takeaways:
- The core of inheritance is the “is-a” relationship; the subclass must be a type of the superclass.
- Subclasses can override superclass methods and call superclass members using super.
- Inheritance makes code more concise and reusable, an important means to achieve code extension and maintenance.
Now, try defining your own superclass and subclass, e.g., “Person” as the superclass and “Student” as the subclass, to experience the power of inheritance!