[Java] Precautions when creating a process that calls a method of Abstract class using DI from a child class

This is a point to note when creating a process to call a method of Abstract class using DI from a child class.

Problematic code

Abstract class


public class AbstractFoo {
    // DI
    public Bar bar; 

    protected void update() {
        bar.update();
    }

}

Child class


public class ChildFoo extends AbstractFoo {
    // DI
    public Bar bar; 

    public void updateChild() {
        //Execute update method of Abstract class
        update(); 
    }

}

Execution result

When executing the updateChild method of the child class, the update method of the called parent class fails with NullPointerException.

Workaround

Child class DI public Bar bar; (Comment out below for clarity)

Revised

Abstract class


public class AbstractFoo {
    // DI
    public Bar bar; 

    protected void update() {
        bar.update();
    }

}

Child class


public class ChildFoo extends AbstractFoo {
    // DI
    // public Bar bar; 

    public void updateChild() {
        //Execute update method of Abstract class
        update(); 
    }

}

Impressions etc.

Overwrite the contents of DI by the declaration in the child class → Since it has not been passed to the Abstract class, the result is that bar is null in the Abstract class. In the child class, the content declared in the Abstract class is inherited, so it is not necessary to declare it again in the first place, but ... As the processing content (description content) increases, it is easy to overlook it and carelessly, so be careful.

Recommended Posts

[Java] Precautions when creating a process that calls a method of Abstract class using DI from a child class
[Java] Wrapper that executes private method of object from outside class
Cause of is not visible when calling a method of another class in java
I made a Wrapper that calls KNP from Java
[Java] Precautions when referencing a reference type in a parent class and instantiating it in a child class
Example of using abstract class
[Java] JUnit that NG if a method with a large number of lines is detected using black magic
[Java] How to get to the front of a specific string using the String class
I made a class that can use JUMAN and KNP from Java
I tried to make a program that searches for the target class from the process that is overloaded with Java
Creating a matrix class in Java Part 1
Precautions when migrating from VB6.0 to JAVA
Increment with the third argument of iterate method of Stream class added from Java9