본문 바로가기
Programming/Java, Spring

[Java 기초문법] constructors / getters & setters

by Renechoi 2022. 10. 17.

[Java 기초문법] by Professional Java Developer Career Starter: Java Foundations @ Udemy

 

 

constructors

 

 

 



컨스트럭터의 개념 

아래의 두 메소드를 컨스트럭터라고 할수있다.

 

 

 

1. they don't return anything 

2. purpose of constructor is basically initialize the object of the property 

 

 


앞에서 클래스는 blueprint라고 비유했다. 
person 같은 개념을 구상할 때 속성을 갖는다 = propertities. 

ex) 사람이라고 하면 name을 갖는다 

프로그래밍을 할 때 object가 속성을 갖도록 forced 된다는 것을 의미한다. 

컨스트럭터는 that would allow us to ensure that these properties are being set. 


위의 첫번째 constructor는 no arg constructor = no input is needed 

두번째는 변수를 받고 있음 

이렇게 두가지 방식으로 만들 수 있음 



실제로 작동하는 방식을 살펴보자 .


Person을 만들기. 

 

 

 

 

 

 

 

 

즉 속성을 정의해주고 부여해주기 위해. 

 

그런데 no arg default도 있다. 

 

일반적으로 변수를 받지 않는 메소드를 만들어 놓고 쓰는 경우는 흔하지 않다. 

 

그렇다면 왜 이게 필요할까? 

 

 

 

 

만약 이렇게 변수를 받지 않는 메소드를 지웠다고 치면 다음과 같은 코드에서 에러가 발생 

 

 

 

컨스트럭터를 다 지운 상태라면 이게 유효하다 

 

 

 

 

 

이 부분이 자바의 constructor 개념에서 재밌는 부분이다 

 

if you create a Java class and you do not write any constructor at all, Java will give you a free no arg default constructor. 

 

근데 만약에 다른 constructor가 있다면 your own construcor => 

자바가 더 이상 free no arg defeult constructor를 제공해주지 않는다 

 

이렇게 자동으로 생성해주는 기능이 있기 때문에 no arg default를 만들고 private로 처리

 

 

 

intellij에서 자동으로 생성해주는 기능을 제공 

 

 

 


Getters and Setters 

 

 

 

 

일반적인 형식은 다음과 같다

 

 

 

public String getFirstName() {
    return firstName;
}

public String setFirstName(){
    this.firstName = firstName;
}

 

왜 이것이 필요할까? 

 

 

이러한 fields가 존재한다고 할 때 

 

 

일반적으로 내부적인 사용을 위해 private를 쓰는데 

 

외부와 소통하기 위해 getters와 setters 메소드를 이용한다

 

그렇다면 public을 사용하면 되지 않을까? 하는 의문이 든다. 

 

하지만 java에서는 convention하게 that is considered a bad pattern to do. 

 

expose를 via getters and setters 

 

by using these, you can control the level of protectiveness 

 

접근에 대한 강도를 조절할 수 있다. 

 

 

 

 

예를 들어 Johnny의 firstname을 추출한다고 해보자. 

 

 

 

만약 Johnny라는 이름의 capital이 소문자로 입력되었는데 받을 때 capital로 받고 싶으면 ? 

 

upper 기능을 Getter에서 설정해줄 수 있다. <= getter의 사용 효용이 드러나는 부분 

 

 

public String getFirstName() {
    return firstName.substring(0,1).toUpperCase() + firstName.substring(1);
}

 

 

 

마찬가지로 setter도 설정해줄 수 있다. 

 

 

여기서 this는 ambiguity를 해소하기 위한 기능인데 이 method 안의 변수를 지칭

 

 

 

 

//

 

getter과 setter 사용의 기본적인 로직은 internal data에 대한 보호이다.

 

 

리팩토링 및 오브젝트 패러다임에 있어서의 효용성 => 그냥public으로 처리하고 johhny를 불러오면 코드 수정이 필요할 때 전체를 다 뒤져야 하거나 수정해야 할 수 있음 

 

 

 

 

 

 

 

반응형