I’m trying to implement an interface, but I get the ‘Null-pointer’ exception, but I don’t know why and I don’t know how to avoid it.
class SpaceComposite.java
import java.util.List;
public class SpaceComposite extends SpaceComponent implements ISpaceComposite {
private List<ISpaceComponent> _components;
public SpaceComposite(String _title) {
super(_title);
// TODO Auto-generated constructor stub
}
@Override
public void addComponent(ISpaceComponent component) {
_components.add(component);// HERE IS THE EXCEPTION RAISED
}
}
which derrives from SpaceComponent class
public abstract class SpaceComponent implements ISpaceComponent{
private String _title;
public SpaceComponent(String _title) {
super();
setTitle( _title);
}
interface ISpaceComposite derrives from ISpaceComponent
public interface ISpaceComposite extends ISpaceComponent{
public void addComponent(ISpaceComponent component);
}
public interface ISpaceComponent {
// Title getter/setter
String getTitle();
void setTitle(String title);
// Looking for a specific child
ISpaceComponent findChild(String name);
// We need to test this brave new world
void runTtest();
}
class Demo.class tries to create a SpaceComposite
public static ISpaceComposite createSolarSystem() {
ISpaceComposite solarSystem = new SpaceComposite("The Solar System");
Star theSol = new Star("Sol");
solarSystem.addComponent(theSol);
}
This line generates the exception
public void addComponent(ISpaceComponent component) {
_components.add(component);// HERE IS THE EXCEPTION RAISED
}
but the component ‘component’ is passed to the function, and i can’t look to the List class.
Do you know, what am I doing wrong?
P.S. This code was adopted from C# .NET and in the .NET there is no mistakes..
P.P.S. Guys! You’re right! But so many correct answers…. Really confused, which I should to mark
Where do you instantiate _components? It seems the list is never created.
I would modify the constructor as follows: