How can I access objects created in one method in other methods?
I want to do this so that I don't have create the same object over and over again every time I create a new method, and want to use that object within it. This is the class I am working on:
import BrandPhone.*;
public class Test {
public static void main(String[] args) {
// Creating the object.
Phone myPhone = new Phone();
//Creating another object.
Color color = myPhone.getColor();
}
}
If I try and access the object color
in another new method like the method initialise
seen below, I get an error
saying "cannot find symbol":
import BrandPhone.*;
public class Test {
public static void main(String[] args) {
// Creating the object.
Phone myPhone = new Phone();
//Creating another object.
Color color = myPhone.getColor();
}
public void initialise() {
color.setNum(120); // This gives an error
}
}
To try and solve this issue, I decided to try and declare the object names as class variables at the beginning of the class, outside of any method. This produces errors saying "non- static variable ('object name') cannot be references from a static context".
import BrandPhone.*;
public class Test {
Phone myPhone;
Color color;
public static void main(String[] args) {
// Creating the object.
myPhone = new Phone(); // Produces error.
//Creating another object.
color = myPhone.getColor(); // Produces error.
}
public void initialise() {
color.setNum(120);
}
}
To attempt to solve this issue, I changed the method so that instead of public static void main(String[] args) {...}
I made it public void newObjects() {...}
. This produces yet another error when I try to run it, saying "Class "Assignment.Test" does not have a main method."
I'm very new to Java, so I'm not sure how to tackle this- do all classes have to have a main
method in the form of public static void main(String[] args) {...}
? If so, could I not just start with a main method and leave it empty, and then continue on to make new methods?