I have to share a String[]
across two classes. One class sets the array and the other gets the array. I made four classes. One contains the Array at superclass level and the array is accessed in the subclasses. And one class holds main()
here they are.
ApplicationDataPool.java
public class ApplicationDataPool extends JFrame {
String[] thisContact;
public ApplicationDataPool() {
super("Update Record");
}
public String[] getThisContact() {
return thisContact;
}
public void setThisContact(String[] thisContact) {
this.thisContact = thisContact;
}
}
UpdateProcessStepOneFrame.java
public class UpdateProcessStepOneFrame extends ApplicationDataPool {
public UpdateProcessStepOneFrame() {
String[] something = { "fname", "lname" };
setThisContact(something);
UpdateProcessStepTwoFrame step2 = new UpdateProcessStepTwoFrame();
step2.setVisible(true);
}
}
UpdateProcessStepTwoFrame.java
public class UpdateProcessStepTwoFrame extends ApplicationDataPool{
public UpdateProcessStepTwoFrame(){
String[] theContact = getThisContact();
//Here is the problem
//Exception in thread "main" java.lang.NullPointerException
System.out.println(theContact.length);
}
}
PROBLEM: whenever I access the array anywhere Java throws a NullPointerException
. Why is this happening. How do I rectify it?开发者_运维知识库
Your thisContact
variable is owned by the instance of UpdateProcessStepOneFrame
or UpdateProcessStepTwoFrame
you've created. If you want to share thisContact
between all instances of ApplicationDataPool
you have to defined it as static
. Which means the variable will be owned by the class and not by its instances.
protected static String[] thisContact;
The classes UpdateProcessStepOneFrame
and UpdateProcessStepTwoFrame
don't know about each other so you need to do setThisContact(something)
in the UpdateProcessStepTwoFrame
class in order for getThisContact
to not be null.
there are two different classes...so String[] theContact will be null in second class unless you set it...
The first call to
setThisContact(something);
sets the sets the array for the UpdateProcessStepOneFrame object (via the base class).
Then when you execute this:
UpdateProcessStepTwoFrame step2 = new UpdateProcessStepTwoFrame();
you're creating a new object with its own separate array, which is never initialised and hence throws a NPE on theContact.length
精彩评论