I have the following two classes:
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?
}
}
I am very certain that it’s a very fundamental thing I’m missing here, but what am I actually missing? The Class1 member “randomvariable” is public and so is the class and both classes are in the same project.
What do I have to do to fix this problem?
There are two problems:
Firstly, you’re trying to assign a value to
randomvariablefrommain, without there being an instance ofClass1. This would be okay in an instance method, asrandomvariablewould be implicitlythis.randomvariable– but this is a static method.Secondly, you’re trying to read the value from
Class2.ranMethod, again without there being an instance ofClass1involved.It’s important that you understand what an instance variable is. It’s a value associated with a particular instance of a class. So if you had a class called
Person, you might have a variable calledname. Now inClass2.ranMethod, you’d effectively be writing:That makes no sense – firstly there’s nothing associating this code with
Personat all, and secondly it doesn’t say which person is involved.Likewise within the
mainmethod – there’s no instance, so you haven’t got the context.Here’s an alternative program which does work, so you can see the difference:
As you can tell by the comments, this still isn’t ideal code – but I wanted to stay fairly close to your original code.
However, this now works:
mainis trying to set the value of an instance variable for a particular instance, and likewisepresentPersonis given a reference to an instance as a parameter, so it can find out the value of thenamevariable for that instance.