Java repeats the final object a second time

This cannot be achieved; you cannot create an instance of an object that has already been created:

private void myMethod(){
    final Object object = null;

    object = new Object();
}

Eclipse gives an error message:

The destination local object cannot be assigned to a variable. It must be empty and not use a composite assignment.

However, if you pass this object to another method:

private void _myMethod(Object object){
    object = new Object();
}

It can be achieved!

final form:

private void myMethod(){
    final Object object = null;

    _myMethod(object);
}

private void _myMethod(Object object){
    object = new Object();
}

Can someone explain this to me? This is so confusing how Java works.

+4
source share
3 answers

First of all, the names of your variables make it difficult to explain, therefore:

private void myMethod(){
    final Object finalObject = null;

    _myMethod(finalObject);
}

private void _myMethod(Object methodObject){
    methodObject = new Object();
}

Java . , methodObject finalObject ( ). finalObject - methodObject, , .

. - , .

+4

.

. picure

enter image description here

( ) .

.

.

2 local variables stack .

final, - .

reassign , .

, ,

 final Object object = null

myMethod. ,

.

private void _myMethod(Object object){
    object = new Object(); //Error here
}

Object object , _myMethod.

not final, , reassigned.

final , Object , .

0

java . .

private void myMethod(){
    final Object object = null;

    _myMethod(object);
}

private void _myMethod(Object newObject){
    newObject= new Object();
}

Therefore, newObjectthis is a new reference if the Object type points to the same object that it pointed to object. Note that the reference to the object is final, not a copy of ie newObject . So what you did is the second part, which is really valid.

public class Test{  
   final Object object = null;

private void myMethod(){    
    _myMethod(object);
}

 private void _myMethod(Object newObject){
        object = new Object(); //Error here
    }
}

The above will fail because the object reference is final.

0
source

Source: https://habr.com/ru/post/1540945/


All Articles