[英]Sharing data across 2 classes
I have to share a String[]
across two classes. 我必须在两个类之间共享一个
String[]
。 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.
一个包含超类级别的Array,并在子类中访问该数组。 And one class holds
main()
here they are. 并且一个类在这里持有
main()
。
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
. 问题:每当我在任何地方访问数组时,Java都会抛出
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. 您的
thisContact
变量由您创建的UpdateProcessStepOneFrame
或UpdateProcessStepTwoFrame
实例拥有 。 If you want to share thisContact
between all instances of ApplicationDataPool
you have to defined it as static
. 如果要在
ApplicationDataPool
所有实例之间共享thisContact
,则必须将其定义为static
。 Which means the variable will be owned by the class and not by its instances. 这意味着变量将由类拥有 ,而不是由其实例拥有。
protected static String[] thisContact;
UpdateProcessStepOneFrame
和UpdateProcessStepTwoFrame
类彼此不了解,因此您需要在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). 将集合设置为UpdateProcessStepOneFrame对象的数组(通过基类)。
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 你正在创建一个具有自己独立数组的新对象,该数组永远不会被初始化,因此会在theContact.length上抛出一个NPE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.