C# 클래스와 객체: 견고한 OOP를 위한 기초 다지기
C# 클래스와 객체: 견고한 OOP 기초
이 튜토리얼에서는 예제와 함께 C#에서 클래스와 객체 개념을 학습합니다.
C#은 객체 지향 언어로 애플리케이션을 객체 중심으로 구조화합니다. OOP에서 복잡한 문제를 재사용 가능하고 독립적인 객체들로 분해해 해결합니다.
객체 작업을 위해 다음 활동 필요:
C# 클래스 (Class)
클래스는 객체의 청사진(Blueprint)입니다. 집 설계도처럼 방, 문, 창문, 구조 규칙을 정의합니다. 그 설계도로 지어진 실제 집이 객체입니다.
여러 집이 같은 설계도 공유하듯, 여러 객체가 같은 클래스에서 생성됩니다.
C#에서 클래스 만들기
class ClassName { }
ClassName이라는 클래스 정의. 클래스는 다음 포함 가능:
- 필드(Fields) – 데이터를 저장하는 변수
- 메서드(Methods) – 동작을 수행하는 함수
예시:
class Dog {
// 필드
string breed;
// 메서드
public void Bark() {
// 구현
}
}
- Dog – 클래스 이름
- breed – 필드
- Bark() – 메서드
참고: C#에서 클래스 멤버는 필드와 메서드 모두 포함.
C# 객체 (Object)
객체는 클래스의 인스턴스(Instance)입니다. 예: Dog 클래스로 불독, 저먼 셰퍼드, 퍼그 객체 생성 가능.
클래스 객체 생성
ClassName obj = new ClassName();
new가 객체 생성; obj가 이름. 예:
Dog bullDog = new Dog();
bullDog 객체로 Dog에 정의된 필드와 메서드 접근 가능.
객체로 클래스 멤버 접근
점(.) 연산자로 멤버 접근:
using System;
namespace ClassObject {
class Dog {
string breed;
public void Bark() {
Console.WriteLine("Bark Bark !!");
}
static void Main(string[] args) {
// Dog 객체 생성
Dog bullDog = new Dog();
// 품종 설정
bullDog.breed = "Bull Dog";
Console.WriteLine(bullDog.breed);
// 메서드 호출
bullDog.Bark();
Console.ReadLine();
}
}
}
출력
Bull Dog
Bark Bark !!
bullDog와 점 연산자로 breed와 Bark() 접근.
한 클래스에서 여러 객체 생성
같은 클래스에서 여러 객체 인스턴스화, 각자 고유 데이터 보유:
using System;
namespace ClassObject {
class Employee {
string department;
static void Main(string[] args) {
// 첫 번째 직원
Employee sheeran = new Employee();
sheeran.department = "Development";
Console.WriteLine("Sheeran: " + sheeran.department);
// 두 번째 직원
Employee taylor = new Employee();
taylor.department = "Content Writing";
Console.WriteLine("Taylor: " + taylor.department);
Console.ReadLine();
}
}
}
출력
Sheeran: Development
Taylor: Content Writing
각 객체가 자신만의 department 값 가짐.
다른 클래스에서 객체 생성
객체는 다른 클래스에서도 생성 가능. 예:
using System;
namespace ClassObject {
class Employee {
public string name;
public void Work(string work) {
Console.WriteLine("Work: " + work);
}
}
class EmployeeDrive {
static void Main(string[] args) {
// Employee 객체 생성
Employee e1 = new Employee();
Console.WriteLine("Employee 1");
// 이름 설정
e1.name = "Gloria";
Console.WriteLine("Name: " + e1.name);
// 메서드 호출
e1.Work("Coding");
Console.ReadLine();
}
}
}
출력
Employee 1
Name: Gloria
Work: Coding
EmployeeDrive가 Employee 객체 생성. public 멤버로 클래스 간 접근 가능. 접근 한정자 더 보기: 공식 문서.
왜 객체와 클래스인가?
클래스와 객체는 모듈식 설계 가능케 함. 적 많은 게임에서 단일 Enemy 클래스로 health, ammo, Shoot(), Run() 정의. 각 적 인스턴스는 고유 상태 유지하며 행동 공유.
코드를 객체 중심으로 모델링하면 복잡도 감소, 유지보수성 향상, 재사용성 증진.