1

我有以下两个课程:

public class Class1
{
    public Class1 randomvariable; // Variable declared

    public static void main(String[] args)
    {
        randomvariable = new Class1(); // Variable initialized
    }
}

public class Class2
{
    public static void ranMethod()
    {
        randomvariable.getSomething(); // I can't access the member "randomvariable" here even though it's public and it's in the same project?
    }
}

我很确定这是我在这里遗漏的一个非常基本的东西,但我实际上遗漏了什么?Class1 成员“随机变量”是公共的,类也是公共的,并且两个类都在同一个项目中。我该怎么做才能解决这个问题?

4

2 回答 2

7

有两个问题:

首先,您尝试为randomvariablefrom分配一个值main,而没有Class1. 这在实例方法中是可以的,就像randomvariable隐含的那样this.randomvariable- 但这是一个静态方法。

其次,您Class2.ranMethod再次尝试从中读取值,而没有Class1涉及的实例。

了解什么是实例变量很重要。它是与类的特定实例相关联的值。因此,如果您有一个名为 的类Person,您可能有一个名为 的变量name。现在Class2.ranMethod,你实际上是在写:

name.getSomething();

这是没有意义的——首先,这段代码根本没有关联Person,其次,它没有说明涉及到哪个人。

同样在main方法中 - 没有实例,所以你没有上下文。

这是一个确实有效的替代程序,因此您可以看到不同之处:

public class Person {
    // In real code you should almost *never* have public variables
    // like this. It would normally be private, and you'd expose
    // a public getName() method. It might be final, too, with the value
    // assigned in the constructor.
    public String name;

    public static void main(String[] args) {
        Person x = new Person();
        x.name = "Fred";
        PersonPresenter.displayPerson(x);
    }
}

class PersonPresenter {

    // In a real system this would probably be an instance method
    public static void displayPerson(Person person) {
        System.out.println("I present to you: " + person.name);
    }
}

正如您从评论中看出的那样,这仍然不是理想的代码 - 但我想与您的原始代码保持相当接近。

However, this now works: main is trying to set the value of an instance variable for a particular instance, and likewise presentPerson is given a reference to an instance as a parameter, so it can find out the value of the name variable for that instance.

于 2012-05-20T19:56:44.543 回答
1

When you try to access randomvariable you have to specify where it lives. Since its a non-static class field, you need an instance of Class1 in order to have a randomvariable. For instance:

Class1 randomclass;
randomclass.randomvariable.getSomething();

If it were a static field instead, meaning that only one exists per class instead of one per instance, you could access it with the class name:

Class1.randomvariable.getSomething();
于 2012-05-20T19:56:57.097 回答