final 키워드는 변수, 메서드, 클래스에 사용되며 어떤 곳에서 사용하느냐에 따라 다른 의미를 가진다.
변수(Variable)
변수에 final을 붙이면 변수는 재할당이 불가능하다라는 뜻이다.
primitive type은 값을 변경할 수 없다는 뜻이고, 객체는 내부의 값은 변경할 수 있으나 객체 그 자체를 바꿀 수 없다는 뜻이다.
public class Test {
public static void main(String[] args) {
final Map<String, Integer> map = new HashMap<>();
final Person person = new Person();
final int a = 10;
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
map = new HashMap<>(); // compile error
person.setAge(10);
person.setName("ganji");
person = new Person(); // compile error
a = 20; // compile error
}
}
메서드(Method)
메서드에 final을 붙이면 해당 메서드를 override를 할 수 없게 된다. 일반적으로 상속 시 public, protected의 접근제어자를 가진 메서드나 같은 패키지 안에 있는 default 접근 제어자를 가진 메서드를 override 할 수 있다.
class Person {
private int age;
private int name;
private String hello() {
System.out.println("hello");
}
final String hello2() {
System.out.println("hello2");
}
}
class Student extends Person {
// compile error
@Override
private String hello() {
System.out.println("Child Hello");
}
// OK
private String hello() {
System.out.println("Child Hello");
}
// compile error
private String hello2() {
System.out.println("Child hello2");
}
}
cf) 상속 시 private method와 final method 둘 다 자식클래스에서 접근할 수 없다. 차이는 private method는 자식 클래스에서 같은 이름으로 메서드 생성이 가능하나 final method는 자식 클래스에서 같은 이름으로 메서드를 생성하지 못한다.
클래스(Class)
final 키워드를 클래스에 붙이면 상속 불가능한 클래스가 된다.
클래스 설계 시 재정의 여부를 생각해서 재정의를 불가능하게 한다면 추후 유지보수 차원에서 좋다고 한다.
public final class Integer extends Number implements Comparable<Integer> {
...
}
final의 쓰임을 잘 알고 사용하는 것이 중요하다.
http://www.tcpschool.com/java/java_modifier_accessModifier
https://www.tutorialspoint.com/private-and-final-methods-in-java-programming
https://sabarada.tistory.com/148
'Backend > Java' 카테고리의 다른 글
@Retention (0) | 2022.08.15 |
---|---|
Annotation(@) (0) | 2022.08.15 |
순수 함수란? (0) | 2022.08.12 |
람다식(Lambda Expression), 람다란(Lambda)? (0) | 2022.08.12 |
Reflection(리플렉션) (0) | 2022.08.08 |