This is a point to note when creating a process to call a method of Abstract class using DI from a child class.
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();
}
}
When executing the updateChild method of the child class, the update method of the called parent class fails with NullPointerException.
Child class DI public Bar bar; (Comment out below for clarity)
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();
}
}
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