需要帮助,让两个类互相帮助 [英] Need help to get two classes to assist each other
问题描述
我目前只是愚弄不同的类来测试它们如何一起工作,但我得到一个错误消息在NetBeans,我不能解决。这是我的代码:
class first_class.java
public class first_class {
private second_class state;
int test_tal = 2;
public void test(int n){
if(n> 2){
System.out.println(HELLO);
}
else {
System.out.println(GOODBYE);
}
}
public static void main(String [] args){
state.john();
TestingFunStuff.test(2);
}
}
class second_class
public class second_class {
first_class state;
public int john(){
if(state.test_tal == 2){
return 4;
}
else {
return 5;
}
}
}
显然我无法运行在我的主类中的方法john,因为非静态变量状态不能从静态上下文引用和方法test,因为非静态方法test(int)不能从静态上下文引用 p>
这是什么意思?
netbeans中显示的错误的屏幕截图: http://imageshack.us/photo/my-images/26/funstufffirstclassnetbe.png/
这意味着 state
必须声明为静态成员要从静态方法使用它,或者您需要一个 first_class
的实例,您可以从中访问非静态成员。在后一种情况下,你需要提供一个getter方法(或使它公开,但是ew)。
此外, code> second_class ,所以在编译之后,你会得到一个 NullPointerException
:static或者是否需要一个实例访问实例方法。
我可能建议遵循Java命名约定,使用 camelCase
而不是 under_scores
,并用大写字母开头类名。
i'm currently just fooling around with different classes to test how they work together, but im getting an error message in NetBeans that i cant solve. Here's my code:
class first_class.java
public class first_class {
private second_class state;
int test_tal=2;
public void test (int n) {
if (n>2) {
System.out.println("HELLO");
}
else {
System.out.println("GOODBYE");
}
}
public static void main(String[] args) {
state.john();
TestingFunStuff.test(2);
}
}
class second_class
public class second_class {
first_class state;
public int john () {
if (state.test_tal==2) {
return 4;
}
else {
return 5;
}
}
}
Apparently i can't run the method "john" in my main class, because "non static variable state cannot be referenced from a static context" and the method "test" because "non static method test(int) cannot be referenced from a static context".
What does this mean exactly?
Screenshot of the error shown in netbeans: http://imageshack.us/photo/my-images/26/funstufffirstclassnetbe.png/
It means state
must be declared as a static member if you're going to use it from a static method, or you need an instance of first_class
from which you can access a non-static member. In the latter case, you'll need to provide a getter method (or make it public, but ew).
Also, you don't instantiate an instance of second_class
, so after it compiles, you'll get a NullPointerException
: static or not, there needs to be an instance to access an instance method.
I might recommend following Java naming conventions, use camelCase
instead of under_scores
, and start class names with upper-case letters.
这篇关于需要帮助,让两个类互相帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!