Need help to get two classes to assist each other

2019-07-28 03:18发布

问题:

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/

回答1:

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.



回答2:

The trick here to get rid of the error message is to move the heavy work outside of main. Let's assume that both lines are part of a setup routine.

state.john();
TestingFunStuff.test(2);

We could create a function called setup which contains the two lines.

public void setup() {
    state.john();
    TestingFunStuff.test(2);
}

Now the main routine can call setup instead, and the error is gone.

public static void main(String[] args) {
    setup();
}

However, the other members are correct in that your instantiation needs some cleanup as well. If you are new to objects and getting them to work together might I recommend the Head First Java book. Good first read (note first not reference) and not all that expensive.



回答3:

Classes can have two types of members by initialization: static and dynamic (default). This controls the time the member is allocated.

Static is allocated at class declaration time, so is always available, cannot be inherited/overridden, etc. Dynamic is allocated at class instantiation time, so you have to new your class if you want to access such members...

It is like BSS vs heap (malloc'd) memory in C, if that helps..



标签: java class