简体   繁体   中英

Sharing data across 2 classes

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;

UpdateProcessStepOneFrameUpdateProcessStepTwoFrame类彼此不了解,因此您需要在UpdateProcessStepTwoFrame类中执行setThisContact(something) ,以使getThisContact不为null。

有两个不同的类...所以String [] theContact在第二个类中将为null,除非你设置它...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM