从一个类获取价值以在另一个类中使用它(java) [英] Get value from one class to use it in another class (java)
问题描述
我有两节课
ABC类
double a = 0.5
public double lala()
{
return a;
}
我想在另一个类中使用它,让我们说DEF类
I want use it in another class, let us say class DEF
ABC abc;
double baba = abc.lala();
但是它说java.lang.NullPointerException,你知道吗?谢谢
But it says that java.lang.NullPointerException, any idea? Thx
public class AdapterDB
{
double cal;
double rcarbohydrate;
double rfat;
double rprotein;
public AdapterDB(double cal, double rcarbohydrate, double rfat, double rprotein, Context ctx)
{
this.cal = cal;
this.rcarbohydrate = rcarbohydrate;
this.rfat = rfat;
this.rprotein = rprotein;
this.context = ctx;
DBHelper = new DatabaseHelper (context);
}
public double Calorie()
{
return cal;
}
public double Carbohydrate()
{
return rcarbohydrate;
}
public double Protein()
{
return rprotein;
}
public double Fat()
{
return rfat;
}
}
这是我的ABC类的代码,我想在另一类> _<
Here is my code for class ABC, and I want to use some of them at another class >_<
推荐答案
您需要在内存中分配ABC,否则它指向 null
,因此出现NullPointerException:
You need to allocate ABC in memory, otherwise it points to null
, hence NullPointerException:
ABC abc = new ABC();
double baba = abc.lala();
编辑:好的,以防ABC没有零参数的构造函数,如:
Edit: Ok, in case ABC does not have a zero-argument constructor like:
public ABC() { }
您有两种选择来解决您的问题.要么添加一个,然后在内部将其他字段的默认值赋予默认值.喜欢:
you have two options to solve your problem. Either add one and inside give default values to your other fields. Like:
public AdapterDB()
{
DBHelper = new DatabaseHelper (context);
}
或者,修改对象的创建,例如:
Or, modify the creation of the object like:
double p1 = <some value>;
double p2 = <some value>;
double p3 = <some value>;
double p4 = <some value>;
Context ctx = new Context(); // don't know what this does.
ABC abc = new ABC(p1, p2, p3, p4, context);
double baba = abc.lala();
这篇关于从一个类获取价值以在另一个类中使用它(java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!