Instantiate public object inside method

I'm trying to instantiate an object inside a method of a class so it can be used anywhere in the class. I come from a python background and it is quite easy, you can just pass the instantiated object to an instance of it's "self" like below.

self.camera = CameraInstance()

How do you do this in Java? I tried something like below but it doesn't like it.

private void init_camera_settings() {
    public CameraInterface camera;
    camera.TakePhoto()
}

private void someotherMethod() {
    camera.TakePhoto()
}

Both methods are in the same class. The reason for this is because I only want to instantiate the camera object only in certain scenarios.

Thanks!

Jon Skeet
people
quotationmark

You can't declare a field inside a method. In Java, a type either has a field, or it doesn't. Every instance of the same class has the same set of fields.

But you can declare the field (not in a method) and decide to only assign a value to it in a method:

// Note: avoid public fields
public CameraInterface camera;

private void initCameraSettings() {
    camera = new Camera();
}

private void someotherMethod() {
    camera.takePhoto();
}

(The field will have a default value, in this case null, until you assign a different value to it.)

As an aside, I'd strongly advise against public fields. I make every field private, and add properties to allow access where necessary. This allows you to change implementation details later. The one exception to this is public static final fields of immutable types, basically for constants, but even there I'd be cautious.

people

See more on this question at Stackoverflow