我有以下两个类:
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?
}
}
Run Code Online (Sandbox Code Playgroud)
我非常肯定这是我在这里缺少的一个非常基本的东西,但实际上我错过了什么?Class1成员"randomvariable"是公共的,类也是如此,两个类都在同一个项目中.我该怎么做才能解决这个问题?
有两个问题:
首先,你试图为randomvariablefrom 赋值main,而不是有一个实例Class1.这在一个实例方法中是可以的,就像randomvariable隐式一样this.randomvariable- 但这是一个静态方法.
其次,你试图从中读取值Class2.ranMethod,同样没有Class1涉及的实例.
了解实例变量是很重要的.它是与类的特定实例相关联的值.因此,如果您有一个被调用的类Person,您可能会调用一个变量name.现在Class2.ranMethod,你有效地写作:
name.getSomething();
Run Code Online (Sandbox Code Playgroud)
这没有任何意义 - 首先,没有任何关联此代码的内容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);
}
}
Run Code Online (Sandbox Code Playgroud)
正如您在评论中所说,这仍然不是理想的代码 - 但我希望保持与原始代码非常接近.
但是,这现在可以工作:main尝试为特定实例设置实例变量的值,同样presentPerson给出对实例的引用作为参数,因此它可以找出该实例的name变量值.
| 归档时间: |
|
| 查看次数: |
1269 次 |
| 最近记录: |