When making a instance of another class, i have noticed the positioning of where you create the instance can either provoke a lot of errors, or work. Let me use this example
public class Main() {
Main(){
}
Camera camera = new Camera();
public static void main(String[] args) {
Box box = new Box();
}
}
What is the difference between these two different instances? I have a slight idea it has to do with static referencing but i am not sure. Also, under what conditions would you create a instance inside or outside of the static main? Thank you for your time.
In the code you have presented, Main
is a class, with a constructor Main()
, a field camera
of type Camera
(with package-local visibility), and a static method main(String[])
. Note that the static method main(String[])
is not the same as the class Main
or its constructor Main()
.
The box
instance of type Box
is created inside the static method main
, and is not visible outside it, while the camera
instance of type Camera
is visible to every class in the same package as the current class.
Also, since camera
is not a static field, it must be associated with an instance of type Main
. For example, you can do this:
Main m = new Main();
Camera thisCamera = m.camera;
But not this:
Camera myCamera = Main.camera;