目次
- 1 1. Introduction
- 2 2. What Is Java Inheritance?
- 3 3. How the extends Keyword Works
- 4 4. Method Overriding and the super Keyword
- 5 5. Advantages and Disadvantages of Inheritance
- 6 6. Differences Between Inheritance and Interfaces
- 7 7. Best Practices for Using Inheritance
- 8 8. Summary
- 9 9. Frequently Asked Questions (FAQ)
1. Introduction
Java is a programming language widely used in various fields, from enterprise systems to web applications and Android development. Among its many features, “inheritance” is one of the most essential concepts when learning object-oriented programming. By using inheritance, a new class (subclass/child class) can take over the functionality of an existing class (superclass/parent class). This helps reduce code duplication and makes programs easier to extend and maintain. In Java, inheritance is implemented using theextends keyword. In this article, we clearly explain the role of the extends keyword in Java, its basic usage, practical applications, and common questions. This guide is useful not only for beginners in Java but also for those who want to review inheritance. By the end, you will fully understand the advantages and disadvantages of inheritance as well as important design considerations. Let’s start by taking a closer look at “What is inheritance in Java?”2. What Is Java Inheritance?
Java inheritance is a mechanism in which one class (the superclass/parent class) passes its characteristics and functionality to another class (the subclass/child class). With inheritance, fields (variables) and methods (functions) defined in the parent class can be reused in the child class. This mechanism makes it easier to organize and manage code, centralize shared processes, and flexibly extend or modify functionality. Inheritance is one of the three core pillars of Object-Oriented Programming (OOP), alongside encapsulation and polymorphism.About the “is-a” Relationship
A common example of inheritance is the “is-a relationship.” For instance, “a Dog is an Animal.” This means that theDog class inherits from the Animal class. A Dog can take on the characteristics and behaviors of an Animal while adding its own unique features.class Animal {
void eat() {
System.out.println("食べる");
}
}
class Dog extends Animal {
void bark() {
System.out.println("ワンワン");
}
}In this example, the Dog class inherits from the Animal class. An instance of Dog can use both the bark method and the inherited eat method.What Happens When You Use Inheritance?
- You can centralize shared logic and data in the parent class, reducing the need to write the same code repeatedly in each subclass.
- Each subclass can add its own unique behavior or override the parent class’s methods.
3. How the extends Keyword Works
The extends keyword in Java explicitly declares class inheritance. When a child class inherits the functionality of a parent class, the syntax extends ParentClassName is used in the class declaration. This allows the child class to use all public members (fields and methods) of the parent class directly.Basic Syntax
class ParentClass {
// Fields and methods of the parent class
}
class ChildClass extends ParentClass {
// Fields and methods unique to the child class
}For example, using the earlier Animal and Dog classes, we get:class Animal {
void eat() {
System.out.println("食べる");
}
}
class Dog extends Animal {
void bark() {
System.out.println("ワンワン");
}
}By writing Dog extends Animal, the Dog class inherits from the Animal class and can use the eat method.Using Parent Class Members
With inheritance, an instance of the child class can access the parent class’s methods and fields (as long as access modifiers allow it):Dog dog = new Dog();
dog.eat(); // Calls the parent class method
dog.bark(); // Calls the child class method
Important Notes
- Java allows inheritance from only one class (single inheritance). You cannot specify multiple classes after
extends. - If you want to prevent inheritance, you can use the
finalmodifier on the class.
Practical Development Tips
Usingextends properly allows you to centralize common functionality in a parent class and extend or customize behavior in subclasses. It is also useful when you want to add new features without modifying existing code.4. Method Overriding and the super Keyword
When using inheritance, there are cases where you want to change the behavior of a method defined in the parent class. This is called “method overriding.” In Java, overriding is done by defining a method in the child class with the same name and the same parameter list as the method in the parent class.Method Overriding
When overriding a method, it is common to add the@Override annotation. This helps the compiler detect accidental mistakes such as incorrect method names or signatures.class Animal {
void eat() {
System.out.println("食べる");
}
}
class Dog extends Animal {
@Override
void eat() {
System.out.println("ドッグフードを食べる");
}
}In this example, the Dog class overrides the eat method. When calling eat on a Dog instance, the output will be “ドッグフードを食べる”.Dog dog = new Dog();
dog.eat(); // Displays: ドッグフードを食べる
Using the super Keyword
If you want to call the parent class’s original method inside an overridden method, use the super keyword.class Dog extends Animal {
@Override
void eat() {
super.eat(); // Calls the parent class’s eat()
System.out.println("ドッグフードも食べる");
}
}This executes the parent class’s eat method first and then adds the subclass’s behavior.Constructors and super
If the parent class has a constructor with parameters, the child class must explicitly call it using super(arguments) as the first line of its constructor.class Animal {
Animal(String name) {
System.out.println("Animal: " + name);
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
System.out.println("Dog: " + name);
}
}Summary
- Overriding means redefining a parent class method in the child class.
- Using the
@Overrideannotation is recommended. - Use
superwhen you want to reuse the parent class’s method implementation. superis also used when calling parent constructors.
5. Advantages and Disadvantages of Inheritance
Using inheritance in Java brings many benefits to program design and development. However, incorrect use can lead to serious issues. Below, we explain the advantages and disadvantages in detail.Advantages of Inheritance
- Improved code reusability Defining shared logic and data in the parent class eliminates the need to repeat the same code in each subclass. This reduces duplication and improves maintainability and readability.
- Easier extension When new functionality is needed, you can create a new subclass based on the parent class without modifying existing code. This minimizes change impact and reduces the chance of bugs.
- Enables polymorphism Inheritance allows “a variable of the parent class to reference an instance of the child class.” This enables flexible design using common interfaces and polymorphic behavior.
Disadvantages of Inheritance
- Deep hierarchies make design complex If inheritance chains grow too deep, it becomes difficult to understand where behavior is defined, making maintenance harder.
- Changes in the parent class affect all subclasses Modifying parent class behavior may unintentionally cause problems across all subclasses. Parent classes require careful design and updates.
- Can reduce design flexibility Overusing inheritance tightly couples classes, making future changes difficult. In some cases, “has-a” relationships using composition are more flexible than “is-a” inheritance.
Summary
Inheritance is powerful, but relying on it for everything can cause long-term issues. Always verify whether a true “is-a relationship” exists and apply inheritance only when appropriate.6. Differences Between Inheritance and Interfaces
Java provides two important mechanisms for extending and organizing functionality: class inheritance (extends) and interfaces (implements). Both support code reuse and flexible design, but their structure and intended usage differ significantly. Below, we explain the differences and how to choose between them.Differences Between extends and implements
- extends (Inheritance)
- You can inherit from only one class (single inheritance).
- Fields and fully implemented methods from the parent class can be used directly in the subclass.
- Represents an “is-a relationship” (e.g., a Dog is an Animal).
- implements (Interface Implementation)
- Multiple interfaces can be implemented simultaneously.
- Interfaces contain only method declarations (though default methods exist from Java 8 onward).
- Represents a “can-do relationship” (e.g., a Dog can bark, a Dog can walk).
Example of Using Interfaces
interface Walkable {
void walk();
}
interface Barkable {
void bark();
}
class Dog implements Walkable, Barkable {
public void walk() {
System.out.println("歩く");
}
public void bark() {
System.out.println("ワンワン");
}
}In this example, the Dog class implements two interfaces, Walkable and Barkable, providing behavior similar to multiple inheritance.
Why Interfaces Are Necessary
Java forbids multiple inheritance of classes because it can create conflicts when parent classes define the same methods or fields. Interfaces solve this problem by allowing a class to adopt multiple “types” without inheriting conflicting implementations.How to Use Them Properly
- Use
extendswhen a clear “is-a relationship” exists between classes. - Use
implementswhen you want to provide common behavior contracts across multiple classes.
Examples:
- “A Dog is an Animal” →
Dog extends Animal - “A Dog can walk and can bark” →
Dog implements Walkable, Barkable
Summary
- A class can inherit from only one parent class, but it can implement multiple interfaces.
- Choosing between inheritance and interfaces based on design intent leads to clean, flexible, and maintainable code.
7. Best Practices for Using Inheritance
Inheritance in Java is powerful, but improper use can make a program rigid and difficult to maintain. Below are best practices and guidelines for using inheritance safely and effectively.When to Use Inheritance — and When to Avoid It
- Use inheritance when:
- A clear “is-a relationship” exists (e.g., a Dog is an Animal).
- You want to reuse parent class functionality and extend it.
- You want to eliminate redundant code and centralize common logic.
- Avoid inheritance when:
- You are using it only for code reuse (this often leads to unnatural class design).
- A “has-a relationship” is more appropriate — in such cases, consider composition.
Choosing Between Inheritance and Composition
- Inheritance (
extends): is-a relationship - Example:
Dog extends Animal - Useful when the subclass truly represents a type of the superclass.
- Composition (has-a relationship)
- Example: A Car has an Engine
- Uses an instance of another class internally to add functionality.
- More flexible and easier to adapt to future changes.
Design Guidelines to Prevent Misuse of Inheritance
- Do not make inheritance hierarchies too deep (keep to 3 levels or fewer).
- If many subclasses inherit from the same parent, re-evaluate whether the parent’s responsibilities are appropriate.
- Always consider the risk that changes in the parent class will affect all subclasses.
- Before applying inheritance, consider alternatives such as interfaces and composition.
Limiting Inheritance with the final Modifier
- Adding
finalto a class prevents it from being inherited. - Adding
finalto a method prevents it from being overridden by subclasses.
final class Utility {
// This class cannot be inherited
}
class Base {
final void show() {
System.out.println("オーバーライド禁止");
}
}Enhancing Documentation and Comments
- Documenting inheritance relationships and class design intentions in Javadoc or comments makes future maintenance far easier.
Summary
Inheritance is convenient, but it must be used intentionally. Always ask, “Is this class truly a kind of its parent class?” If unsure, consider composition or interfaces as alternatives.8. Summary
Up to this point, we have explained Java inheritance and theextends keyword in detail—from the fundamentals to practical usage. Below is a recap of the key points covered in this article.- Java inheritance allows a subclass to take over the data and functionality of a superclass, enabling efficient and reusable program design.
- The
extendskeyword clarifies the relationship between a parent and child class (the “is-a relationship”). - Method overriding and the
superkeyword make it possible to extend or customize inherited behavior. - Inheritance offers many advantages, such as code reuse, extensibility, and support for polymorphism, but also has drawbacks such as deep or complex hierarchies and wide-impact changes.
- Understanding the differences between inheritance, interfaces, and composition is crucial for choosing the right design approach.
- Avoid overusing inheritance; always be clear about the design intent and rationale.
9. Frequently Asked Questions (FAQ)
Q1: What happens to the parent class constructor when a class is inherited in Java? A1: If the parent class has a no-argument (default) constructor, it is automatically called from the child class constructor. If the parent class only has a constructor with parameters, the child class must explicitly call it usingsuper(arguments) at the beginning of its constructor. Q2: Can Java perform multiple inheritance of classes? A2: No. Java does not support multiple inheritance of classes. A class can extend only one parent class using extends. However, a class can implement multiple interfaces using implements. Q3: What is the difference between inheritance and composition? A3: Inheritance represents an “is-a relationship,” where the child class reuses the functionality and data of the parent class. Composition represents a “has-a relationship,” in which a class contains an instance of another class. Composition often offers more flexibility and is preferable in many cases requiring loose coupling or future extensibility. Q4: Does the final modifier restrict inheritance and overriding? A4: Yes. If a class is marked as final, it cannot be inherited. If a method is marked as final, it cannot be overridden in a subclass. This is useful for ensuring consistent behavior or for security purposes. Q5: What happens if the parent and child class define fields or methods with the same name? A5: If a field with the same name is defined in both classes, the field in the child class hides the one in the parent class (shadowing). Methods behave differently: if the signatures match, the child method overrides the parent method. Note that fields cannot be overridden—only hidden. Q6: What happens if inheritance depth becomes too large? A6: Deep inheritance hierarchies make code harder to understand and maintain. It becomes difficult to track where logic is defined. For maintainable design, try to keep inheritance depth shallow and roles clearly separated. Q7: What is the difference between overriding and overloading? A7: Overriding redefines a method from the parent class in the child class. Overloading defines multiple methods in the same class with the same name but different parameter types or counts. Q8: How should abstract classes and interfaces be used differently? A8: Abstract classes are used when you want to provide shared implementation or fields among related classes. Interfaces are used when you want to define behavior contracts that multiple classes can implement. Use an abstract class for shared code and an interface when representing multiple types or when multiple “abilities” are needed.
