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
thisContactvariable is owned by the instance ofUpdateProcessStepOneFrameorUpdateProcessStepTwoFrameyou’ve created. If you want to sharethisContactbetween all instances ofApplicationDataPoolyou have to defined it asstatic. Which means the variable will be owned by the class and not by its instances.