I recently in java and today I saw such a thing. Create a class object and immediately after it open curly brackets ... and write code in them. Like this

private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() { @Override public void onOpened(@NonNull CameraDevice cameraDevice) { // This method is called when the camera is opened. We start camera preview here. mCameraOpenCloseLock.release(); mCameraDevice = cameraDevice; createCameraPreviewSession(); } @Override public void onDisconnected(@NonNull CameraDevice cameraDevice) { mCameraOpenCloseLock.release(); cameraDevice.close(); mCameraDevice = null; } @Override public void onError(@NonNull CameraDevice cameraDevice, int error) { mCameraOpenCloseLock.release(); cameraDevice.close(); mCameraDevice = null; Activity activity = getActivity(); if (null != activity) { activity.finish(); } } }; 

The instance and brackets are defined immediately and 4 methods are redefined inside. What does this even mean? How will this work?

    1 answer 1

    This is called anonymous class . Immediately after calling the constructor, the necessary methods were implemented. If a class is created based on an interface, then it will be necessary to write an implementation of all the methods. If this is just a class, then only the necessary methods can be redefined.