需要帮助以帮助两堂课互相帮助 [英] Need help to get two classes to assist each other

查看:47
本文介绍了需要帮助以帮助两堂课互相帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在鬼混使用不同的类来测试它们如何协同工作,但是我在NetBeans中收到了我无法解决的错误消息.这是我的代码:

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

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);

}
}

second_class类

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)不能从静态上下文引用".

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".

这到底是什么意思?

netbeans中显示的错误的屏幕截图: http://imageshack.us/photo/my-images/26/funstufffirstclassnetbe.png/

Screenshot of the error shown in netbeans: http://imageshack.us/photo/my-images/26/funstufffirstclassnetbe.png/

推荐答案

这意味着如果要通过静态方法使用它,则必须将 state 声明为静态成员. first_class 的实例,您可以从中访问非静态成员.在后一种情况下,您需要提供一种getter方法(或将其公开,但是要公开).

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).

此外,您没有实例化 second_class 的实例,因此在编译后,您将得到 NullPointerException :是否为静态,需要有一个实例访问实例方法.

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.

我可能建议您遵循Java命名约定,使用 camelCase 代替 under_scores ,并以大写字母开头类名.

I might recommend following Java naming conventions, use camelCase instead of under_scores, and start class names with upper-case letters.

这篇关于需要帮助以帮助两堂课互相帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆