메소드 매개 변수의 최종 키워드
이 질문에는 이미 답변이 있습니다.
종종 다음과 같은 방법이 있습니다.
public void foo(final String a, final int[] b, final Object1 c){
}
이 메소드가 최종 매개 변수를 전달하지 않고 호출되면 어떻게됩니까? 즉, 나중에 변경 된 Object1 (최종으로 선언되지 않음) 은이 메소드에 잘 전달 될 수 있습니다.
Java는 항상 매개 변수의 사본을 작성하여 메소드로 전송합니다. 이것은 최종 코드가 호출 코드의 차이를 의미하지 않는다는 것을 의미합니다. 이는 메소드 내에서 변수를 재 할당 할 수 없음을 의미합니다. 최종 객체가있는 경우 객체의 속성을 계속 변경할 수 있습니다.
최종 선언 해야하는 상황이 있습니다. 그렇지 않으면 컴파일 오류가 발생합니다. 즉, 익명 클래스로 전달합니다. 기본 예 :
public FileFilter createFileExtensionFilter(final String extension) {
FileFilter fileFilter = new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().endsWith(extension);
}
};
// What would happen when it's allowed to change extension here?
// extension = "foo";
return fileFilter;
}
final
수정자를 제거하면 더 이상 값이 런타임 상수라는 보장이 없으므로 컴파일 오류가 발생합니다. 익명 클래스 외부에서 값을 변경하면 익명 클래스 인스턴스가 작성된 순간에 다르게 작동합니다.
Java는 가치에 지나지 않습니다. (또는 더 나은-값으로 전달 참조)
따라서 전달 된 인수와 메소드 내의 인수 는 동일한 객체 (값)를 가리키는 두 개의 다른 핸들러입니다.
따라서 객체 의 상태 를 변경 하면 객체를 참조하는 다른 모든 변수에 반영됩니다. 그러나 인수에 새 객체 (값)를 다시 할당하면이 객체 (값)를 가리키는 다른 변수가 다시 할당되지 않습니다.
final
메소드 매개 변수 의 키워드는 호출자에게 전혀 의미가 없습니다. 또한 존재 여부가 바이트 코드를 변경하지 않기 때문에 실행중인 프로그램에는 전혀 의미가 없습니다. 매개 변수 변수가 메소드 내에서 재 할당되는 경우에만 컴파일러가 불만을 표시하도록합니다. 그게 다야. 그러나 이것으로 충분합니다.
나와 같은 일부 프로그래머는 이것이 매우 좋은 것으로 생각하고 final
거의 모든 매개 변수에 사용합니다. 길고 복잡한 방법을 더 쉽게 이해할 수 있습니다 (길고 복잡한 방법은 리팩토링해야한다고 주장 할 수 있습니다). 또한 로 표시 되지 않은 방법 매개 변수에 대해 주목을 final
받습니다.
이 foo () 구현을 고려하십시오.
public void foo(final String a) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.print(a);
}
});
}
Runnable
인스턴스가 메소드보다 오래 지속 되기 때문에 final
키워드 없이 컴파일되지 않습니다 final
. 나중에 참조를 위해 참조 사본을 가져가도 안전하다는 것을 컴파일러에 알립니다. 따라서 value가 아닌 final로 간주 되는 참조 입니다 . 다시 말해, 발신자로서, 당신은 아무것도 엉망으로 만들 수 없습니다 ...
final 은 해당 변수의 값이 할당 된 후에는 변경할 수 없음을 의미합니다.
한편, 이러한 메소드에서 인수에 final 을 사용 하면 메소드 실행 중에 프로그래머가 값을 변경할 수 없습니다 . 이는 메소드 내에서 최종 변수를 재 할당 할 수 없음을 의미합니다.
매개 변수를 final로 선언하면 해당 값을 변경할 수 없습니다.
class Bike11 {
int cube(final int n) {
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]) {
Bike11 b=new Bike11();
b.cube(5);
}
}
출력 : 컴파일 시간 오류
자세한 내용은 내 블로그를 방문하십시오 : http://javabyroopam.blogspot.com
문자열은 변경할 수 없으므로 나중에 문자열을 변경할 수 없습니다 (String 개체를 보유한 변수가 다른 String 개체를 가리 키도록 할 수만 있습니다).
However, that is not the reason why you can bind any variable to a final
parameter. All the compiler checks is that the parameter is not reassigned within the method. This is good for documentation purposes, arguably good style, and may even help optimize the byte code for speed (although this seems not to do very much in practice).
But even if you do reassign a parameter within a method, the caller doesn't notice that, because java does all parameter passing by value. After the sequence
a = someObject();
process(a);
the fields of a may have changed, but a is still the same object it was before. In pass-by-reference languages this may not be true.
@stuXnet, I could make the exact opposite argument. If you pass an object to a function, and you change the properties of the passed object then the caller of the function will see the changed value in its variable. This implies a pass by reference system, not pass by value.
What is confusing is the definition of pass by value or pass by reference in a system where the use of pointers is completely hidden to the end user.
Java is definitely NOT pass by value, as to be such, would mean one could mutate the passed object and the original would be unaffected.
Notice you cannot mutate primitives you can only assign them to variables. So testing a Pass by reference or by value by using primitives is not a test.
What you cannot do in Java that can be done in other languages is to reassign the caller's variables to a new value because there are no pointers in Java, so this makes it confusing.
final keyword in the method input parameter is not needed. Java creates a copy of the reference to the object, so putting final on it doesn't make the object final but just the reference, which doesn't make sense
참고URL : https://stackoverflow.com/questions/2236599/final-keyword-in-method-parameters
'Programing' 카테고리의 다른 글
if-else 블록에서 'if (0)'블록의 목적은 무엇입니까? (0) | 2020.06.20 |
---|---|
Android Facebook 4.0 SDK 이메일, 생년월일 및 사용자 성별을 얻는 방법 (0) | 2020.06.20 |
정규식을 사용하여 줄이 비어 있는지 확인하는 방법 (0) | 2020.06.20 |
UnicodeEncodeError : 'charmap'코덱이 문자를 인코딩 할 수 없습니다 (0) | 2020.06.20 |
Spring Data JPA에 커스텀 메소드를 추가하는 방법 (0) | 2020.06.20 |