[1주차] 자바 클래스

송수용·2022년 3월 21일
0

웹 개발의 봄, Spring

목록 보기
4/25

클래스 이해하기

흔히 클래스를 공부할 때 빵틀에 비유하곤 했다.
빵틀이 어쨋다는건가 항상 생각하긴 했었는데 그래서 나는
큰 상위 개념안에 하위 개념이 들어가있다고 나 혼자 정의를 내렸었다.

예를 들면 자동차라는 큰 틀안에 여러가지 차종이 있는 것.
노트북이라는 카테고리안에 여러가지 스펙의 노트북 등
이렇게 이해해왔다.

예제로 본 클래스를 보자.

package com.sparta.week01.prac;

public class Course {
 
  public String title;
  public String tutor;
  public int days;
}

강의라는 큰 카테고리에 강의의 특징을 담았다.
강사와 제목 수강기간
큰 카테고리인 "강의" 라는 것은 바뀌지 않지만, 강의의 속성이나 특징은 언제든지 변경될 수 있다.

public static void main(String[] args) {
    Course course = new Course();
    course.title = "웹개발의 봄, Spring";
    course.tutor = "남병관";
    course.days = 60;
    
    System.out.println(course.title);
    System.out.println(course.tutor);

    Course course2 = new Course();
    course2.title = "프론트엔드의 꽃, react";
    course2.tutor = "임민영";
    course2.days = 60;
    System.out.println(course2.title);
    System.out.println(course2.tutor);
  }
}

똑같이 큰 카테고리의 강의지만, 서로 다른 객체가 나올 수 있다.

package com.sparta.week01.prac;

public class Course {
  // title, tutor, days 가 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;
  }

this를 활용해서 정확하게 정보를 해당 클래스에 삽입할 수 있다.
this를 주석 처리한 결과 값은 null이 나오게 된다.

  public static void main(String[] args) {
    String title = "웹개발의 봄 Spring";
    String tutor = "남병관";
    int days = 60;
    Course course = new Course(title,tutor,days);
    System.out.println(course.title);
    System.out.println(course.tutor);
    System.out.println(course.days);
  }
}
profile
#공부중 #협업 #소통중시 #백엔드개발자 #능동적 #워커홀릭 #스파르타코딩 #항해99 #미니튜터 #Nudge #ENTJ #브레인스토밍 #아이디어뱅크

0개의 댓글