[Java] Getter, Setter

호호빵·2022년 5월 24일
0

Java

목록 보기
6/19

Getter, Setter

Getter - 정보를 가져오는 메소드

Setter - 정보를 바꾸는 메소드

# Course.java
public class Course {
    public String title;
    public String tutor;
    public int days;

    // 생성자
    public Course(String title, String tutor, int days) {
        this.title = title;
        this.tutor = tutor;
        this.days = days;
    }
}

# 멤버변수 선언이 public -> private 
  private String title;
  private String tutor;
  private int days;

  // 생성자

  # Setter 메소드
  public void setTitle(String title) {
      this.title = title;
  }
  public void setTutor(String tutor) {
      this.tutor = tutor;
  }
  public void setDays(int days) {
      this.days = days;
  }
  
  
  # Getter 메소드
  public String getTitle() {
  	return this.title;
  }
  public String getTutor() {
  	return this.tutor;
  }
  public String getDays() {
  	return this.days;
  }

# Prac.java
public class Prac {
    public static void main(String[] args) {

        String title = "웹개발의 봄, Spring";
        String tutor = "남병관";
        int days = 35;
        Course course = new Course();
        course.title = title;
        course.tutor = tutor;
        course.days = days;
        System.out.println(course.title);
        System.out.println(course.tutor);

    }
}

# 멤버변수 선언이 public -> private 
	String title = "웹개발의 봄, Spring";
        String tutor = "남병관";
        int days = 35;
        Course course = new Course();
        course.setTitle(title);		// 메소드 사용
        course.setTutor(tutor);
        course.setDays(days);
        System.out.println(course.getTitle()); // 메소드 사용
        System.out.println(course.getTutor());
profile
하루에 한 개념씩

0개의 댓글

관련 채용 정보