플러터 (flutter)

Dart Class - 프로젝트1_1

CreatoMaestro 2023. 6. 14. 22:18
반응형

1. 클래스에 관하여

객체지향 프로그래밍은 코드를 여러 객체로 나누고 그 객체를 모아 프로그래밍을 구성한다.

여기서 객체는 하나의 역할을 수행하는 코드의 모음이라고 생각하면 된다.

 

클래스는 하나의 객체를 구성하는 요소를 표현한 것이다.

 

이렇게만 말하면 이해하기 힘드니 예시하나 들어본다.

 

대학에서 교수와 학생의 정보를 관리하는 프로그램을 만들려고 한다.

 

교수의 경우 이름, 전공, 직책, 강의하는 과목을 관리하고,

강의를 새로 등록하는 함수와 강의를 확인하는 함수를 만들려고 한다.

 

학생의 경우 이름, 전공, 학년, 수강 중인 수업을 관리하고,

수업을 새로 등록하는 함수와 수업을 확인하는 함수를 만든다.

 

이 때 우리는 교수 클래스와 학생 클래스를 만들어 사람이 들어오거나 나갈 때 큰 어려움 없이 추가할 수 있다.

이를 표로 정리하면 다음과 같다.

클래스 이름 교수 학생
변수 이름, 전공, 직책, 강의하는 과목 이름, 전공, 학년, 수강 중인 수업
함수 (메소드) 강의 등록 함수, 강의 확인 함수 수업 등록 함수, 수업 확인 함수

이제부터 클래스에 대해 배우면서 실제 코드를 작성해 보자.

 

2. 클래스 기본

import 'dart:io';

//교수 클래스
class professor {
  //변수 목록
  String name;
  String major;
  String position;
  List<String> lecture;

  //생성자
  professor(String name, String major, String position, List<String> lecture)
      : this.name = name,
        this.major = major,
        this.position = position,
        this.lecture = lecture;

  //정보 확인 함수
  void check_info() {
    print("name : ${this.name}");
    print("major : ${this.major}");
    print("position : ${this.position}");
    print("lecture : ${this.lecture}");
  }
}

//학생 클래스
class student {
  //변수 목록
  String name;
  String major;
  String grade;
  List<String> lecture;

  //생성자
  student(String name, String major, String grade, List<String> lecture)
      : this.name = name,
        this.major = major,
        this.grade = grade,
        this.lecture = lecture;

  //정보 확인 함수
  void check_info() {
    print("name : ${this.name}");
    print("major : ${this.major}");
    print("grade : ${this.grade}");
    print("lecture : ${this.lecture}");
  }
}

void main() {
  //교수 인스턴스 생성
  professor professor1 = professor(
      "name1",
      "Electric engineering",
      "assistant professor",
      ["electromagnetic", "python 1", "communication system"]);

  //학생 인스턴스 생성
  student student1 =
      student("name2", "Computer science", "3", ["data science", "AI lecture"]);

  //교수 정보 확인
  print("Check professor");
  professor1.check_info();

  //학생 정보 확인
  print("\nCheck student");
  student1.check_info();
}

Class 실행 결과
실행 결과

코드가 상당히 길어보이지만 하나하나 뜯어보면 간단한 기능을 하는 코드이다.

하나씩 뜯어가면서 어떤 기능을 하는지 살펴보자

 

2-1) 클래스 선언과 변수

class professor {
  //변수 목록
  String name;
  String major;
  String position;
  List<String> lecture;

클래스 선언을 위해서는 앞에 'class'를 적어준다.

우리가 변수를 선언할 때 'int a'와 같이 적어주는 것과 비슷하다고 생각하면 된다.

중괄호 안에 클래스를 구성할 요소들을 적어주면 된다.

 

변수는 우리가 변수 선언한 것과 똑같이 적어주면 된다.

이 변수들은 우리가 클래스를 이용해 하나의 객체를 만들 때 같이 만들어지는 변수들이다.

 

2-2) 클래스 생성자

클래스 생성자는 클래스를 선언할 때 사용하는 함수이다.

생성자의 이름은 클래스의 이름과 동일하게 한다.

생성자의 구조는 다음과 같다.

//생성자

클래스 이름(생성자 실행 시 받을 파라미터들):
	this.변수1  = 변수1,
    this.변수2  = 변수2;

클래스 이름을 적어주고 소괄호 안에 클래스 생성 시 받을 파라미터를 적는다.

이 파라미터를 이용하여 클래스 안의 변수를 초기화한다.

코드 안에서는 다음과 같이 생성자를 선언했다.

  //생성자
  professor(String name, String major, String position, List<String> lecture)
      : this.name = name,
        this.major = major,
        this.position = position,
        this.lecture = lecture;

여기서 this가 의미하는 것은 생성자가 포함되어 있는 클래스를 의미한다.

this.name은 professor 클래스 안에 있는 name이라는 변수를 의미한다.

 

생성자를 통해 클래스 인스턴스를 생성할 때는 다음과 같이 쓴다.

(인스턴스 : 클래스를 이용해 생성된 객체를 의미)

professor professor1 = professor(
      "name1", //name
      "Electric engineering", // major
      "assistant professor", // position
      ["electromagnetic", "python 1", "communication system"]); // lecture

변수의 타입을 클래스 이름으로 쓰고 변수 이름을 쓴 다음 생성자를 호출해 그 안에 객체를 집어넣는다.

professor 생성자 안에 4개의 파라미터 값이 들어간 것을 볼 수 있다.

2-3) 클래스 메서드(method)

클래스 메서드는 클래스 안에 있는 함수이다.

이 함수는 클래스 안에 있는 변수들을 이용해 특정 역할을 수행한다. 

 

예를 들어 professor 클래스의 check_info함수는 professor 클래스 안에 있는 변수들을 print하는 역할을 한다.

메서드를 선언하는 방법은 함수를 선언하는 방법과 동일하다.

  //정보 확인 함수
  void check_info() {
    print("name : ${this.name}");
    print("major : ${this.major}");
    print("position : ${this.position}");
    print("lecture : ${this.lecture}");
  }

 

클래스에서 선언되어 있는 메서드를 사용하는 방법은 다음과 같다.

  professor1.check_info();

클래스의 인스턴스 뒤에 '.'을 붙이고 그 뒤에 메서드를 호출해준다.

이렇게 하면 professor1이라는 인스턴스 안에 있는 check_info 메서드를 호출한다.

 

이 3가지 요소가 클래스의 기본 구성 요소이다.

예제의 student 클래스도 동일한 방식으로 선언되었다.

 

3. 상속과 오버라이드(override)

'클래스의 기본'에서 쓴 코드 안에는 다른 클래스 안에 같은 변수와 비슷한 기능을 하는 메서드가 있다.

이러한 중복을 줄여주기 위해 상속이라는 개념을 사용한다.

 

상속은 클래스를 선언할 때 다른 클래스에 있는 변수와 메서드를 가져온다.

코드를 통해 어떻게 하는지 알아보자

//부모 클래스
class person {
  String name;
  String major;
  List<String> lecture;

  person(this.name, this.major, this.lecture);

  void check_info() {
    print("name : ${this.name}");
    print("major : ${this.major}");
    print("lecture : ${this.lecture}");
  }
}

우선 베이스가 되는 클래스를 생성해준다.

이 안에는 professor와 student class에 모두 있는 변수와 메서드를 넣어 주었다.

//교수 클래스
class professor extends person {
  //변수 목록
  String position;

  //생성자
  professor(String name, String major, String position, List<String> lecture)
      : this.position = position,
        super(name, major, lecture);

  //정보 확인 함수 (override)
  @override
  void check_info() {
    print("name : ${this.name}");
    print("major : ${this.major}");
    print("position : ${this.position}");
    print("lecture : ${this.lecture}");
  }
}

3-1) extends와 super

베이스가 되는 person 클래스를 상속해준 professor 클래스는 나타낸 코드이다.

상속을 위해서 extends를 사용한다.

class '상속 받는 클래스' extend '상속할 클래스' 와 같은 방식으로 선언한다.

 

professor 클래스가 person 클래스를 상속받음으로써 person 클래스 안에 있는 name, major, lecture 변수와 check_info 함수를 얻어온다.

때문에 추가로 이 변수를 써주지 않아도 된다.

 

생성자를 보면 super라는 새로운 단어가 나온다.

super가 의미하는 것은 상속 받은 클래스이다.

그렇기 때문에 생성자 안에 있는 super(name, major, lecture)는 상속 받은 클래스인 person의 생성자를 호출한 것이다.

position의 경우 person 안에 없기 때문에 따로 초기화를 시켜주었다.

 

3-2) 오버라이드 (override)

오버라이드는 상속 받은 메서드가 다른 기능을 하도록 만든다.

@override
void check_info() {
  print("name : ${this.name}");
  print("major : ${this.major}");
  print("position : ${this.position}");
  print("lecture : ${this.lecture}");
}

오버라이드 되는 메서드 위에는 @override를 써준다.

person안에 있는 check_info 메서드와 비교를 하면 position을 추가로 print하는 것을 볼 수 있다.

아래는 person의 check_info 코드이다.

void check_info() {
    print("name : ${this.name}");
    print("major : ${this.major}");
    print("lecture : ${this.lecture}");
}

 

아래는 상속까지 있는 전체 코드이다.

//부모 클래스
class person {
  String name;
  String major;
  List<String> lecture;

  person(this.name, this.major, this.lecture);

  void check_info() {
    print("name : ${this.name}");
    print("major : ${this.major}");
    print("lecture : ${this.lecture}");
  }
}

//교수 클래스
class professor extends person {
  //변수 목록
  String position;

  //생성자
  professor(String name, String major, String position, List<String> lecture)
      : this.position = position,
        super(name, major, lecture);

  //정보 확인 함수 (override)
  @override
  void check_info() {
    print("name : ${this.name}");
    print("major : ${this.major}");
    print("position : ${this.position}");
    print("lecture : ${this.lecture}");
  }
}

//학생 클래스
class student extends person {
  //변수 목록
  String grade;

  //생성자
  student(String name, String major, String grade, List<String> lecture)
      : this.grade = grade,
        super(name, major, lecture);

  //정보 확인 함수
  @override
  void check_info() {
    print("name : ${this.name}");
    print("major : ${this.major}");
    print("grade : ${this.grade}");
    print("lecture : ${this.lecture}");
  }
}

void main() {
  //교수 인스턴스 생성
  professor professor1 = professor(
      "name1", //name
      "Electric engineering", // major
      "assistant professor", // position
      ["electromagnetic", "python 1", "communication system"]); // lecture

  //학생 인스턴스 생성
  student student1 =
      student("name2", "Computer science", "3", ["data science", "AI lecture"]);

  //교수 정보 확인
  print("Check professor");
  professor1.check_info();

  //학생 정보 확인
  print("\nCheck student");
  student1.check_info();
}

 

반응형