# property

```kotlin
//생성자 앞에 키워드가 없다면 Field.
class Person(firstName: String, lastName: String, age: Int)

//생성자 앞에 var 혹은 val과 같은 키워드가 붙는다면 Property.
class Person(val firstName: String, val lastName: String, val age: Int)


//생성은 둘다 똑같은 방법으로 한다.
val person = Person("k", "H", 345)
val person2 = Person2("k", "H", 345)
```

```java
//java
//기존의 Java에서의 방식이 이랬다면...
public class PersonJava {

    String firstName;
    String lastName;
    int age;

    public PersonJava(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getFirstNam() { return firstName; }

    public String getLastName() { return lastName; }   

    public int getAge() { return age; }

    public void setFirstNam(String firstName){ this.firstNam = firstName; }

    public void setLastName(String lastName){ this.lastName = lastName; }

    public void setAge(int age){ this.age = age; }

}
```

```kotlin
//kotlin
//Kotlin에서는 이 정도면 끝난다.
//프로퍼티로 선언을 하면 내부적으로 알아서 getter, setter를 만들어주기 때문에 보일러플레이트가 사라진다.
class PersonKotlin(var firstName: String, var lastName: String, var age: Int)
```

* 필드로 만드는 것과 프로퍼티로 만드는 것의 가장 큰 차이는 내부적으로 getter, setter가 만들어지느냐 아니냐의 차이다.
* 필드로 생성하면 내부적으로 getter, setter가 만들어지지 않는다.
* 프로퍼티로 선언을 해야지만 내부적으로 getter, setter가 만들어진다. (val은 자바의 final과 같이 불변이므로 내부적으로 getter는 만들어지지만, setter는 만들어지지 않는다.)
* public, private, protected 와 같은 접근제한자도 자바에서와 동일하게 사용할 수 있고, 접근제한자만 잘 사용한다면 보일러플레이트들을 많이 제거할 수 있다.

필드를 하나 선언을 하고 그 바로 밑에 get(), set() 함수를 만들어 커스텀 getter, setter를 만들수도 있다.

```kotlin
//kotlin
class Person {

    var name: String = ""
        get() = field.toUpperCase() //프로퍼티의 실제 값에 접근해서 가져올때 field. 로 접근한다.
        set(value) { //set()으로 받아온 값을 value로 표시.
            field = "Name : " + value
        }

    var name1: String = ""
        get() {
            field.toUpperCase()
            return "aaa"
        }
        set(value) {
            field = "Name : " + value
        }
}

var person = Person()

person.name = "test"
println(person.name)    //NAME : TEST

person.name1 = "test"
println(person.name1)    //aaa
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gold.gitbook.io/kotlin/class/property.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
