JAVA

Getter 와 Setter

영카이브 2024. 1. 7. 20:52
  • 캡슐화란 데이터구조에 사용하는 것을 한 곳으로 모아둔 것이다.
  • 클래스의 내부 데이터 구조가 변경된다는 것은 클래스의 멤버 변수나 필드 구성이 변경된다는 것을 의미한다.
  • 즉 데이터 계층화에 따라서 종속되는 문제를 해결하기위해 캡슐화를 쓰는것이며 단순 속성명이 변경되기 때문은 아니다. 
  • 데이터 구조를 정의하는 속성만 있고 메서드를 가지고있지않은것은 캡슐화 된것이 아니다.
  • 또한 다른 캡슐에 있는 보조데이터의 속성을 쓰기 위해서는 메서드를 통해 해결한다.
  • 그 메서드가 Getter와 Setter이다. 

 

public class Product {
	String name;
	int price; 
	int quantity;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	public int getQuantity() {
		return quantity;
	}
	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}
	
}

 

public class Inventory {
	private Product[] products;
	private int current; 
	
	public Inventory() {
		this(5);
	}	
	
	public Inventory(int size) {
		this.products = new Product[size]; 
		this.current=0; 
	}
	
	public void addInventory() {
		Scanner sc = new Scanner(System.in);
		System.out.println("상품 입력");
		
		String name; 
		int price, quantity;
		
		System.out.printf("상품 이름 : "); 
		name=sc.next();
		do {
			System.out.print("가격 : ");
			price=sc.nextInt();
			if(price<0) {
				System.out.println("가격은 0보다 커야합니다.");
			}
		}while(price<0);
		do {
			System.out.print("수량 : ");
			quantity=sc.nextInt();
			if(quantity<0) {
				System.out.println("수량은 0보다 커야합니다.");
			}
		}while(quantity<0);
        
        // Setter적용
		Product product = new Product();
		product.setName(name);
		product.setPrice(price);
		product.setQuantity(quantity);
		
		Product[] products = this.products; 
		int size = this.current; 
		if(products.length==size) {
			// 1.크기가 3개정도 더 큰 새로운 배열을 생성
			Product[] temp = new Product[size+3]; 
			// 2.값을 이주 
			for( int i=0; i<size; i++) {
				temp[i]=products[i]; 
			}
			// 3.inventory.products가 새로 만든 temp배열을 참조
			products = temp;
			 /*
			 이 부분 추가 
			 temp 배열을 products에 할당했지만, 이는 지역 변수에 할당된 것이기 때문에 메소드가 종료되면서 사라지게 됩니다 
			 따라서 this.products에 다시 할당
			 */
			this.products=products;
		}
		products[size]=product;
		current++;
	}
	public void displayInventory() {
		// 집중화 코드 
		this.displayInventory(this.current);
	}
	
	// overload
	// 넘겨받은 size값만큼 출력
	public void displayInventory(int size) {
		System.out.println("상품 출력");
		for( int i=0; i<size; i++) {
        	// Getter 적용
			Product product = this.products[i]; 
			String name = product.getName(); 
			int price = product.getPrice();
			int quantity = product.getQuantity();
			System.out.println( "상품 이름 : " + name);
			System.out.println( "상품 가격 : " + price);
			System.out.println( "상품 수량 : " + quantity);
		}		
	}
}

 

 

 

Getter와 Setter를 쓰는 이유

 

직접 접근을 사용하면 내부 구조 변경 시 해당 부분을 직접 수정해야 하지만, Getter와 Setter를 사용하면 외부에서의 접근이 제한되어 내부 구조 변경에 영향을 덜 받게 된다. 이는 코드 유지보수의 편의성을 높일 수 있다.

 
 
예시
 
Exam클래스의 kor, eng, math변수를 중간에 Subject 클래스로 묶어 데이터 구조 변경이 일어났다.
 

 

직접 접근

int korScore = exam.kor;

public class Exam {
    int kor;
    int eng;
    int math;	
    int seq;
}

 

 

int korScore = exam.subject.kor;

subject가 추가되므로 로직이 복잡할 시 수정할 코드가 대량으로 늘어난다.

public class Exam {
    Subject subject;
    int seq;
}

public class Subject {
    int kor;
    int eng;
    int math;
}

 

 

 

Getter 와 Setter 접근

int korScore = exam.getKor();

public class Exam {
	int kor;
	int eng;
	int math;
	int seq;

	public int getKor() {
		return kor;
	}
	public void setKor(int kor) {
		this.kor = kor;
	}
	public int getEng() {
		return eng;
	}
	public void setEng(int eng) {
		this.eng = eng;
	}
	public int getMath() {
		return math;
	}
	public void setMath(int math) {
		this.math = math;
	}
	public int getSeq() {
		return seq;
	}
	public void setSeq(int seq) {
		this.seq = seq;
	}
}

 

 

똑같이 int korScore = exam.getKor();

public class Exam {
	Subject subject;
	int eng;
	int math;
	int seq;

    public int getKor() {
		return subject.getKor;
	}
	public void setKor(int kor) {
		this.kor = subject.setKor;
	}
	public int getEng() {
		return subject.getEng;
	}
	public void setEng(int eng) {
		this.eng = subject.Eng;
	}
	public int getMath() {
		return subject.getMath;
	}
	public void setMath(int math) {
		this.math = subject.setMath;
	}
	public int getSeq() {
		return seq;
	}
	public void setSeq(int seq) {
		this.seq = seq;
	}
}

public class Subject {
    int kor;
    int eng;
    int math;
    
    public int getKor() {
		return kor;
	}
	public void setKor(int kor) {
		this.kor = kor;
	}
	public int getEng() {
		return eng;
	}
	public void setEng(int eng) {
		this.eng = eng;
	}
	public int getMath() {
		return math;
	}
	public void setMath(int math) {
		this.math = math;
	}
}
 
 
 
 
 

참고 자료 출처 : https://www.youtube.com/watch?v=cStPUeKgSCU