study

Getter, Setter

_드레 2021. 4. 28. 12:01

java class - 밖에 드러내도 되는 것, 누구나 사용 : public

             - 함부로 바꾸면 안되는 것, 보안 : private 

 

    public static void main(String[] args) {
        //Course course = new Course();
        //course라는 클래스를 만들었으므로 변수로 사용할수있다.

        String title = "웹개발의 봄, Spring";
        String tutor = "남병관";
        int days = 35;
        Course course = new Course(title, tutor, days);
        //course.title = title(); 를 아래로 수정
        course.setTitle(title);
        course.setTutor(tutor);
        course.setDays(days);

        //System.out.println(course.title); 를 아래로 수정
        //setter를 썼기때문에 조회가 안됨. 조회하려면 getter를 써야햐
        //Course.java안에서 getter써주고 여기서 호출
        System.out.println(course.getTitle());
        System.out.println(course.getTutor());
        System.out.println(course.getDays());
        
        }
package com.sparta.week01.prac;

public class Course {
    // title, tutor, days 가 Course 라는 맥락 아래에서 의도가 분명히 드러나죠!
    private String title;
    private String tutor;
    private int days;
    //private로 바꾸면 ~ ~ ~ 정해진 방법으로만 값을 바꿀 수 있음.
    // 그게 setter

    //기본 생성자
    public Course() {
    }
    //생성자가 아예 없으면 기본생성자가 자동으로 생성되지만
    //하나라도 생성자를 추가할경우 기본생성자는 없어지므로 함께 추가해주어야함

    //생성자
    public Course(String title, String tutor, int days) {
        //course라는 변수명이 Course클래스 내에선 없기때문에 얘는 모름 ㅠ
        //"나", "내가받은" 이라는 의미로 this를 쓰면 알수있움.
        this.title = title;
        this.tutor = tutor;
        this.days = days;
    }

    // Setter 쓰기위해 메소드 선언
    // 밖에서 호출이 되어야 하니까 public 리턴타입 메소드명(재료) { 명령 }
    // 돌려주는게 없다 void , set+멤버변수명 첫번째 글자를 대문자로
    // 밖에서 받는 재료는 String title
    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 반환타입 메소드명(재료) {
        명령
                return 반환값;
    }*/
    public String getTitle() {
        return this.title;
    }

    public String getTutor() {
        return this.tutor;
    }

    public int getDays() {
        return this.days;
    }

}
package com.sparta.week01.prac;

public class Tutor {
    private String name;
    private String bio;

/*    public Tutor (String name, String bio){
        this.name = name;
        this.bio = bio;
    }*/

    //기본생성자 꼭 써주기 (다른생성자 쓰고있으니까)
    public Tutor() {

    }

    public Tutor(String name, String bio) {
        this.name = name;
        this.bio = bio;
    }

    public String getName() {
        return this.name;
    }

    public String getBio() {
        return this.bio;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setBio(String bio) {
        this.bio = bio;
    }

}