ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 23.01.14 Kotlin Class와 field
    개발 이야기/TIL 2023. 1. 14. 22:00

    JAVA랑 Kotlin이랑 비슷하다고 했던거 같은데... 으음 공부하다보니 다른 부분들이 꽤나 많은 것 같다. 

    오늘은 Kotlin의 Class에 관해서 JAVA와 비교해서 이것저것을 정리해보려고 한다. 

    아래의 코드를 기반으로 설명을 시작해보자. 

    //JAVA
    
    public class Button {
       private int width;
       private int height;
       //constructor
       public Button(int width, int height){
       	this.width = width
        this.height = height
       }
       //getter
       public int getWidth(){
       	return width;
       }
       public int getHeight(){
       	return height;
       }
        public void setWidth(int value){
            if(value>50){
                width = value
            }
            else{
                width=50
            }
        }
        public void setHeight(int value){
            if(value>50){
                height = value
            }
            else{
                width=50
            }
        }
        
    }
    public static void main(String[] args) {
        Button b1 = new Button()
        Scanner sc = new Scanner(System.in);
    	b1.height = (int)sc.nextLine();
        b1.width = (int)sc.nextLine();
        System.out.println(b1.width+b1.height)
    }
    //kotlin
    class Button {
        var width: Int = 0
        var height: Int = 0
        get() = field
        set(value){
            if(value>50){
                field = value
            }
            else{
                field=50
            }
        }
        
    }
    fun main(args: Array<String>) {
        val b1 = Button()
        b1.height = readLine()!!.toInt()
        b1.width = readLine()!!.toInt()
    
        println(b1.width+b1.height)
    }

    Class 선언 차이 

    JAVA: 접근 제한자, class, 이름{}

    Kotlin: (접근제한자), class, 이름{}

     

    Constructor(생성자)

    JAVA에서는 생성자를 만들 때 아래와 같이 만들었다. 

    즉, 각 parameter의 경우에 따라 생성자를 따로 선언해주는 방식을 가졌다.

    public class Button {
       private int width;
       private int height;
       //Constructor
       public Button(int width, int height){
       	this.width = width
        this.height = height
       }

    Kotlin에서는 아래와 같이 class class이름()을 통해 생성자를 정의할 수 있다. 

    이때도 동일하게 다양한 case에 관해 다루려면 constructor로 이를 표현 가능하다.

    class Button(val width:Int, val height:Int){
        var width: Int = 0
        var height: Int = 0
     }
    class Button{
        var width: Int = 0
        var height: Int = 0
        constructor(width: Int){
        	this.width = width
        }
        constructor(width: Int, height:Int){
        	this.width = width
            thist.height=height
        }
     }

    혹은 ()를 통해 주생성자를 만들어준 경우에는 constructor로 아래에 적어준 것은 부생성자이기에 주생서자에게 생성을 위임해주어야한다(:this(witdth))

    class Button(var width:Int){
     
    //에러 발생 
    //    constructor(width:Int, height: Int){
    //    	this.height = height
    //    }
    
    	constructor(width:Int, height: Int):this(width){
       		this.height = height    
            }
     }

    init을 이용한 초기화 

    자바에서 생성자의 파라미터로 받은 값의 유효성을 확인하는 경우가 있는데 이는 보통 아래의 코드와 같다. 

    public class Button {
       private int width;
       private int height;
       //constructor
       public Button(int width, int height){
       	if(this.width.isEmpty()||this.heigth.isEmpty()){
        	throw new IllegealArgumentException("Error")
        }
        else{
        	this.width = width
        	this.height = height}
       }
     }

    코틀린에서는 init블록을 통해 이를 할 수 있다. init블록에서는 클래스의 객체가 생성될 때 실행되는 초기화 코드가 들어간다. 

    //kotlin
    class Button(width:Int, height:Int){
        var width: Int
        var height: Int
    	
        init{
        	if(width.isEmpty()){
                heigth = 0
            }
             if(height.isEmpty()){
                heigth = 0
            }
            this.width=width
            this.height=height
        }
    }

    Setter&Getter 

    이 글을 오늘 쓰게 된 main파트이다. Setter와 Getter와 Field!

    우선 JAVA에서는 아래와 같이 getter와 setter에 관한 함수를 각 property마다 만들어주었어야했다.

    public class Button {
       private int width;
       private int height;
       //constructor
       public Button(int width, int height){
       	this.width = width
        this.height = height
       }
       //getter
       public int getWidth(){
       	return width;
       }
       public int getHeight(){
       	return height;
       }
        public void setWidth(int value){
            if(value>50){
                width = value
            }
            else{
                width=50
            }
        }
        public void setHeight(int value){
            if(value>50){
                height = value
            }
            else{
                width=50
            }
        }
        
    }

    코틀린에서는 조금 다르다.

    우선 아래와 같이 쓰면 끝이다. 

    //kotlin
    class Button(var width:Int, var height:Int) {
    }

    기본적으로 클래스에서 주 constructor로 선언만 해도 getter와 setter를 자동적으로 선언해준다. 

    동시에 kotlin에서는 기본적으로 생략되어있는 경우 public이다. 따라서 개발자가 따로 getter와 setter를 선언해줄 필요가 없다. 

    이때 ()안에 변수에 따라 다르긴하다. 

    var로 하냐, val로 하냐에 따라 다른데, var의 경우 알다시피 variable 즉, 변경이 가능한 변수이다. 따라서 getter와 setter가 모두 선언된다. 반면 val의 경우 값 변경이 불가하기에 getter만 만들어진다. 만약, valr, val을 모두 쓰지 않고 이름과 자료형만 적었다면? 이 경우 생성자 매개변수로 들어가 getter와 setter가 생성되지 않는다.

    class 선언방식 Getter 생성 여부 Setter 생성 여부 
    class Button(width:Int) X X
    Oclass Button(var width:Int) O O
    class Button(val width:Int) O X

    getter와 setter 커스텀하기

    자동으로 만들어주기는 하지만, 내가 직접 만들고 싶으면 아래와 같이 작성하면 된다. 

    이 때 feild를 사용한다. field란 무엇일까? 이는 Backing feld라 한다. 

    Backing filed란 프로퍼티의 값을 저장하기 위한 필드이다. 이를 만일 사용하지 않고 set을 하려고 한다면, 무한재귀에 빠지는 경우가 발생한다!

    따라서 아래와 같이 꼭 field 키워드를 사용하도록 하자.

    //kotlin
    class Button {
        var width: Int = 0
        var height: Int = 0
        get() = field
     // height이후에 작성한 set이기에 set(value)에 해당하는 field는 height에 관한 값이 됨   
        set(value){
            if(value>50){
                field = value
            }
            else{
                field=50
            }
        }
        
    }

     

Designed by Tistory.