Develop/Salesforce

Getter/Setter Method

HongUniverse 2022. 8. 10. 15:21
반응형

Getter Stter는 왜 그리고 어떻게 쓰는 걸까?

필드, 즉 프로퍼티(속성)을 사용하기 위해서 사용한다.

 

쉽게 말하면,

get -> 값을 읽는다.

set -> 값을 적용, 쓴다.

 

get and set are Accessors, meaning they're able to access data and info in private fields and usually do so from public properties.

-> get과 set은 접근제어자이다. 즉, private 필드의 데이터와 정보에 접근할 수 있고, 공용 프로퍼티에서 접근할 수 있다. 

public class ApexProperties{
	//Using both getters and setters. read-write
	public Integer counter {
    	get{
        	return counter;
        }
        set{
        	counter = value;
        }
    }
}
ApexProperties gettersAndSetters = new ApexProperties();

gettersAndSetters.counter = 5; 			//쓰기
System.debug(gettersAndSetters.counter);	//읽기

 

When using apex getters and setters, additional code is not required. You can use Automatic properties. With automatic properties it allows you to write more compact code.

 

public class AutomaticApexProperties {	
    //Property that is read-write
    public Integer counter{get; set;}
    //Read-only property
    public String name{get;}
    //Write-only property
    public integer writeOnlyCounter {set;}
}
AutomaticApexProperties  gettersAndSetters = new AutomaticApexProperties ();

gettersAndSetters.counter = 25;
System.debug(gettersAndSetters.counter);

//error, getter만 있으므로 쓰기x
gettersAndSetters.name = 'Jack';

//Use set accessor
gettersAndSetters.writeOnlyCounter = 3;

//Error, setter만 있으므로 읽기x
System.debug(gettersAndSetters.writeOnlyCounter);
public Integer counter{get; set;}

위와 같은 과정이지만,  이렇게 한줄로 줄일 수 있다.


Using Static Properties

public class StaticApexproperties {
    //Declare a static integer
    private static integer staticVariable;
    //Declare a class variable
    private integer nonStaticVariable;

  //Static method does not have access to non-static member variables in the class
   public static integer staticProperty { 
     get {return staticVariable;} 
     set { staticVariable = value; } 
   }  
    
   //Non static method must call the class variable
   public integer nonStaticProperty { 
     get {return nonStaticVariable;} 
     set { nonStaticVariable = value; } 
   }     

}

Static 변수는 은 아래와 같이 인스턴스 생성 없이 쓰기와 읽기가 가능하다.

//Initalize class object
StaticApexproperties  gettersAndSetters = new StaticApexproperties ();

//Use set accessor for to access the class variable as it is private
gettersAndSetters.nonStaticProperty = 25;

//Use get accessor to print out private non static variable
System.debug(gettersAndSetters.nonStaticProperty);

//Will cause an error
gettersAndSetters.staticVariable = 15;

//You can call the static variable with the following static property
StaticApexproperties.staticProperty = 15;

System.debug(StaticApexproperties.staticProperty);

 

이렇게 getter와 setter를 이용하여, 클래스 내의 private 필드에 접근할 수 있으며 

static 변수는 인스턴스 생성 없이 읽기와 쓰기가 가능하다는 것을 알아보았다. 

그리고 Automatic properties 를 이용하여 짧게 줄일 수 있다.

반응형