Final Field

invisibleufo101·2024년 9월 14일

Java

목록 보기
7/10
post-thumbnail

A final field can only be initialized once and cannot be modified afterward (similar to const in C++).

Types of final fields:

  1. Static Final Fields: Initialized when declared.

    static final double PI = 3.14159;
  2. Instance Final Fields: Initialized in the constructor.

    public class Person {
        String name;
        final String eyeColor;
        final String socialSecurityNumber;
    
        public Person(String name, String eyeColor, String socialSecurityNumber) {
            this.name = name;
            this.eyeColor = eyeColor;
            this.socialSecurityNumber = socialSecurityNumber;
        }
    }
    
    Person somePerson = new Person("John Doe", "green", "1234-5678");
    
    // This is allowed
    somePerson.name = "Jack Doe";
    
    // This causes an error because 'eyeColor' is final
    somePerson.eyeColor = "blue";  

Final fields can be initialized during the object's creation, but once set, they cannot be changed.

profile
하나씩 차근차근

0개의 댓글