티스토리 뷰

C#

15 class

김윤지. 2023. 6. 13. 18:13

클래스 : 필드(변수), 메소드(함수)로 구성

클래스는 보통 private로 선언 > 클래스 바깥에서 클래스 내부 함수를 바꾸지 못하게 함 (캡슐화의 원칙)

필드는 무조건 private로 선언하고 public 함수로 수정 가능하게 한다

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _014_Class
{
  public class Rectangle
  {
    private int width;
    private int height;

    // Setter
    public void SetWidth(int w)
    {
      if(w >= 0)
        width = w;
      else
        Console.WriteLine("width와 height는 0보다 크거나 같아야 합니다.");
    }
    public void SetHeight(int h)
    {
      if(h >= 0)
        height = h;
      else
        Console.WriteLine("width와 height는 0보다 크거나 같아야 합니다.");
    }
    // Getter 함수: GetWidth(), GetHeight()
    public int GetWidth()
    {
      return width;
    }
    public int GetHeight()
    {
      return height;
    }

    public int Area()
    {
      return width * height;
    }
  }

  public class Date
  {
    private int year, month, day;

    public void SetYear(int year)
    {
      if(year >= 0)
        this.year = year;
    }
    public void SetMonth(int month)
    {
      if (month > 0 && month <= 12)
        this.month = month;
    }
    public void SetDay(int day)
    {
      if (day > 0 && day <= 31)
        this.day = day;
    }

    // Getter
    public int GetYear()
    {
      return this.year;
    }
    public int GetMonth()
    {
      return month;
    }
    public int GetDay()
    {
      return day;
    }

    // 날짜를 출력하는 메소드
    public void Print()
    {
      Console.WriteLine(year + "/" + month + "/" + day);
    }

    // 생성자: 리턴값이 없고 클래스와 같은 이름을 갖는 함수
    public Date(int y, int m, int d)
    {
      year = y;
      month = m;
      day = d;
    }

    public Date()
    {
      year = 1;
      month = 1;
      day = 1;
    }
  }
  public class Program
  {
    static void Main(string[] args)
    {
      // 생성자를 이용해서 날짜를 초기화
      Date today = new Date(2023, 6, 7);
      Console.Write("today :");
      today.Print();

      Date date = new Date(); // date는 Date 클래스의 객체(instance)

      //date.SetYear = 2023;
      date.SetYear(2023);
      date.SetMonth(6);
      date.SetDay(7);

      // 오늘 날짜를 출력하시오 2023/6/7
      Console.WriteLine("{0}/{1}/{2}", 
        date.GetYear(), date.GetMonth(), date.GetDay());
      date.Print();

      Rectangle a = new Rectangle();
      a.SetWidth(10); 
      a.SetHeight(10);

      // 면적을 계산해봐
      // int area = a.width * a.height;
      //int area = a.GetWidth() * a.GetHeight();
      int area = a.Area();
      Console.WriteLine("a의 면적 = {0}", area);
    }
  }
}

실행결과

today :2023/6/7
2023/6/7
2023/6/7
a의 면적 = 100
계속하려면 아무 키나 누르십시오 . . .

 

 

클래스 예제

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _015_strudentScore
{
  internal class Program
  {
    static void Main(string[] args)
    {
      // (1)학생의 학번, 이름, 3개 과목의 점수를 저장하는
      // 클래스를 만들어라(속성: getter, setter 자동)
      // (2) s1과 s2 객체를 만들고 생성자로 초기화해라
      // (3) 학번, 이름, 평균점수를 출력하는 메소드를 만들고 
      // s1과 s2 객체를 출력하라

      Student s1 = new Student();      

      s1.Id = 22615011;
      s1.Name = "홍길동";
      s1.Sub1 = 88;
      s1.Sub2 = 78;
      s1.Sub3 = 90;

      Student s2 
        = new Student(22615021, "아이유", 70, 80, 90);

      s1.Print();
      s2.Print();
    }
  }
}

student class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _015_strudentScore
{
  public class Student
  {
    // (1)학생의 학번, 이름, 3개 과목의 점수를 저장하는
    // 클래스를 만들어라
    //private int id;
    //private string name;
    //private int sub1;
    //private int sub2;
    //private int sub3;

    // 속성은 대문자로
    // public int Id { get; set; }
    public string Name { get; set; }
    public int Sub1 { get; set; }
    public int Sub2 { get; set; }
    public int Sub3 { get; set; }

    // Id는 음수일 수 없다는 조건
    private int id;

    public int Id
    {
      get { return id; }
      set { if(id > 0) id = value; }
    }

    // 생성자
    public Student(int id, string name, int sub1, 
      int sub2, int sub3)
    {
      this.id = id;
      this.Name = name;
      this.Sub1 = sub1;
      this.Sub2 = sub2;
      this.Sub3 = sub3;
    }

    public Student()
    {

    }

    public void Print()
    {
      Console.WriteLine("{0} {1} {2:F2}",
        Id, Name, (Sub1 + Sub2 + Sub3) / 3.0);
    }
  }
}

실행결과

0 홍길동 85.33
22615021 아이유 80.00
계속하려면 아무 키나 누르십시오 . . .

'C#' 카테고리의 다른 글

14 LiveChart  (0) 2023.06.08
14 WPF SQL 완성, 스네이크 게임  (0) 2023.05.31
13 WPF SQL 기능  (0) 2023.05.24
12 WPF SQL 설정 및 디자인  (0) 2023.05.17
11 SQL 설치  (0) 2023.05.17
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함