📟java/개발 이론정리

this || getter(값 불러오기. return사용), setter(값 변경 ,this사용)

하얀성 2023. 10. 2. 11:05

this 키워드

this 키워드는 메소드 수행의 주체 객체를 가리킴. 여기서 this는 c라는 주체객체를 가리킨다.

// 호출 영역
Cookie c = new Cookie("버터링", 1500);
c.setPrice(2000);
// 정의 영역
class Cookie {
  private String name;
  private int price;
  // 생성자
  public Cookie(String name, int price) {
    this.name = name;   // this.name -> 인스턴스 변수
    this.price = price; // this.price -> 인스턴스 변수
  }
  // 세터
  public void setName(String name) {
    this.name = name; // this.name -> 인스턴스 변수
  }
}

 

생성자를 통해서 아래의 코드를 수정가능하지만.. getter와 setter을 통해서도 객체지향 관점에 어울리게 수정이 가능.

class Power {
    public int kick;
    public int punch;
}

public class Example {
    public static void main(String args[]) {
        Power robot = new Power();
        robot.kick = 10;
        robot.punch = 20;
    }
}

<생성자를 통한 수정코드>

class Power {
    private int kick; // private 접근 제한자 사용
    private int punch; // private 접근 제한자 사용
    
    // 생성자를 통한 초기화
    public Power(int kick, int punch) {
        this.kick = kick;
        this.punch = punch;
    }
public class Example {
    public static void main(String args[]) {
        Power robot = new Power(10, 20);
// 생성자를 통해 private 필드인 kick과 punch를 초기화
   }
}

감춰진 필드 가져오기 - 게터(getter)

private 필드

private 필드는 외부에서 직접 값을 가져올(read) 수 없습니다. 이를 외부에서 읽기 위해서는 게터 메소드가 필요합니다.

 

 

게터의 특징?

게터 메소드는 아래의 특징을 갖습니다.

  • private 필드를 반환한다.
  • public 이다.
  • 메소드명은 get + 필드명으로 한다.

* 주의사항

메소드 사용은 인스턴스 객체의 명으로 해야하며,

메소드 뒤에()을 추가해줘야 한다.

 


숨겨진 필드 변경하기 - 세터(setter)

세터의 필요성?

private 필드는 외부에서 직접 값을 변경(write)할 수 없습니다. 이를 해결하기 위해서 세터 메소드가 필요합니다.

 

 

세터의 특징

세터 메소드는 아래의 특징을 갖습니다.

  • private 필드를 변경한다.
  • public 이다.
  • 메소드명은 반환하려는 private 필드명 앞쪽에 set을 붙인다.

 

* 주의사항

 

setter 는 필드값을 새로 설정하기 때문에 ()안에 수정할 값을 기입해야함.

 

아래처럼 매개변수의 값을 필드 변수와 다르게 해주거나, 

this.를 사용해서 다른 변수임을 인지시켜줘야한다.

public void setPassword(String pw) {
    password = pw;
  }  


 

다음 코드를  객제 지향 프로그래밍 관점애소 바람직하게 수정하라.

class Power {
    public int kick;
    public int punch;
}

public class Example {
    public static void main(String args[]) {
        Power robot = new Power();
        robot.kick = 10;
        robot.punch = 20;
    }
}

 

수정 코드:

getter와 setter을 사용하였다.

 

class Power {
    private int kick;
    private int punch;
    
    // Setter Methods
    public void setKick(int kick) {
        this.kick = kick;
    }
    
    public void setPunch(int punch) {
        this.punch = punch;
    }
    
    // Getter Methods
    public int getKick() {
        return kick;
    }
    
    public int getPunch() {
        return punch;
    }
}

public class Example {
    public static void main(String args[]) {
        Power robot = new Power();
        robot.setKick(10); // setter method를 사용하여 필드 값을 설정
        robot.setPunch(20); // setter method를 사용하여 필드 값을 설정
        
        // 필요하다면, getter method를 사용하여 필드 값을 조회
        System.out.println("Robot's kick power: " + robot.getKick());
        System.out.println("Robot's punch power: " + robot.getPunch());
    }
}

실전 응용 문제

 

<제출답안>

public class KnightTest {
  public static void main(String[] args) {
    // 객체 생성
    Knight k1 = new Knight("돈키호테", 30);
    // 정보 출력
    System.out.println("[객체 생성]");
    System.out.printf( "    Knight { name : %s, hp: %d }\n",k1.getName(),k1.getHp());
    
    // 체력 증가: 기존 체력 + 30
    k1.setHp(30);
    // 결과 출력
     System.out.println("[체력 증가 +30]");
     System.out.printf( "    Knight { name : %s, hp: %d }\n",k1.getName(),k1.getHp());
  }
}

class Knight {
  // 필드
  private String name;
  private int hp;
  // 생성자
  public Knight(String name, int hp) {
    this.name = name;
    this.hp = hp;
  }
  // 게터
  public String getName(){
    return name;
  }
  public int getHp(){
    return this.hp;
  }
  // 세터
  public void setHp(int hp){
    this.hp +=  hp;
  }
}

<수정답안>

-> toString 메서드를 통해 불러오도록 함.

public class KnightTest {
    public static void main(String[] args) {
        // 객체 생성
        Knight k1 = new Knight("돈키호테", 30);
        // 정보 출력
        System.out.println("[객체 생성]");
        System.out.println("    " + k1.toString()); // 객체의 정보를 문자열로 변환하여 출력
        
        // 체력 증가: 기존 체력 + 30
        k1.increaseHp(30); // setHp에서 increaseHp로 변경
        // 결과 출력
        System.out.println("[체력 증가 +30]");
        System.out.println("    " + k1.toString()); // 객체의 정보를 문자열로 변환하여 출력
    }
}

class Knight {
    // 필드
    private String name;
    private int hp;
    
    // 생성자
    public Knight(String name, int hp) {
        this.name = name;
        this.hp = hp;
    }
    
    // 게터
    public String getName() {
        return name;
    }

    public int getHp() {
        return hp;
    }
    
    // 체력 증가 메서드
    public void increaseHp(int hp) {
        this.hp += hp;
    }
    
    // 객체의 상태를 문자열로 변환하는 메서드
    public String toString() {
        return String.format("Knight { name : %s, hp: %d }", name, hp);
    }
}

여기서 name과 hp는 Knight 클래스의 인스턴스 변수(필드 변수)입니다. toString() 메서드는 Knight 클래스의 인스턴스에 대해 호출되므로, 이 메서드 내에서는 해당 인스턴스의 name과 hp 필드에 직접 접근할 수 있습니다.

this 키워드를 명시적으로 사용하지 않아도, 인스턴스 메서드 내에서는 해당 인스턴스의 필드에 접근이 가능합니다. 즉, 이 toString() 메서드 내에서 사용된 name과 hp는 호출된 객체의 name과 hp 필드 값을 참조합니다.

 


출처: 그림으로 배우는 자바 객체지향.