Reputation:
I am putting together a simple simulated network in java, where i can add computers, servers, and connect two objects with ethernet ports. This is where the null pointer exception is being thrown, when i call "this.etherPort.addElement(t);"
import java.util.Vector;
public class Server extends Computer{
public Vector<Ethernet> etherPort;
public void addPort(Ethernet t)
{
this.etherPort.addElement(t);
}
}
This code is run when i make a new Ethernet object using this code:
public class Ethernet {
public Computer terminal1, terminal2; public int volume; public Ethernet(Computer term, Server term2) { this.terminal1 = term; this.terminal2 = (Computer) term2; if(term != null) { term.addPort(this); } if(term2 != null) { term2.addPort(this); } } }
Upvotes: 0
Views: 646
Reputation: 30723
You didn't initialize the vector. Should be:
public Vector<Ethernet> etherPort = new Vector<Ethernet>();
Upvotes: 3
Reputation: 46566
You need to instanciate your etherPort member :
public class Server extends Computer{
public Vector<Ethernet> etherPort = new Vector<Ethernet>();
public void addPort(Ethernet t)
{
this.etherPort.addElement(t);
}
}
You should make sure that addPort() is not overriding a method called from your Computer constructor, though. Given the context, I assume it's safe (i.e. Computer has no addPort() method).
As stated below in a comment, it's generally better to use interfaces that don't constrain the containers implementations : you'd better declare etherPort as a
List<Ethernet>
instead of a
Vector<Ethernet>
and use etherPort.add(element) instead of the Vector-specific addElement method.
Upvotes: 10
Reputation: 284786
etherPort is null. You are apparently never initializing it with an actual Vector. I think you want:
public class Server extends Computer{
public Vector<Ethernet> etherPort;
public Server()
{
etherPort = new Vector<Ethernet>();
}
public void addPort(Ethernet t)
{
this.etherPort.addElement(t);
}
}
Upvotes: 2