전체 코드
using System.ComponentModel;
using System.Numerics;
using System.Threading;
namespace CSharp
{
class Knight
{
static public int counter = 1;
public int id;
public int hp;
public int attack;
static public void Test()
{
counter++;
}
static public Knight CreateKnight()
{
Knight knight = new Knight();
knight.hp = 100;
knight.attack = 10;
return knight;
}
public Knight()
{
hp = 100;
attack = 10;
counter++;
Console.WriteLine("생성자 호출");
}
public Knight(int hp) :this()
{
this.hp = hp;
Console.WriteLine("int 생성자 호출");
}
public Knight(int hp, int attack) : this()
{
this.hp = hp;
this.attack = attack;
}
public void Move()
{
Console.WriteLine("Knight Move");
}
public void Attack()
{
Console.WriteLine("Knight Attack");
}
}
internal class Program
{
static void Main(string[] args)
{
Knight knight = new Knight(50,5);
Knight knight2 = new Knight();
knight2.hp = 80;
Knight knight3 = Knight.CreateKnight();
}
}
}
1. static 키워드란?
- 클래스에 속하는 멤버로, 특정 객체에 종속되지 않음
- 객체를 생성하지 않고도 클래스 이름을 통해 직접 접근 가능
- 같은 클래스 타입의 모든 객체가 공유하는 변수 및 메서드를 만들 때 사용
- 메모리에 단 하나만 존재하며, 모든 인스턴스에서 동일한 데이터를 공유
2. static 멤버 vs 인스턴스 멤버
| 구분 | 인스턴스 멤버 | static 멤버 |
|---|
| 소속 | 개별 객체(인스턴스) | 클래스 자체 |
| 메모리 할당 | 각 객체마다 별도로 할당 | 프로그램 시작 시 단 1회 할당 |
| 호출 방식 | 객체를 통해 호출 (객체명.멤버) | 클래스 이름을 통해 호출 (클래스명.멤버) |
| 사용 예 | knight.hp = 100; | Knight.counter++; |
3. static 키워드 예제 코드
using System;
class Knight
{
static public int counter = 0;
public int id;
public int hp;
public int attack;
public Knight()
{
id = counter++;
hp = 100;
attack = 10;
Console.WriteLine($"Knight 생성 (ID: {id})");
}
static public void Test()
{
counter++;
Console.WriteLine("static Test() 호출");
}
static public Knight CreateKnight()
{
Knight knight = new Knight();
knight.hp = 100;
knight.attack = 10;
return knight;
}
}
class Program
{
static void Main(string[] args)
{
Knight.Test();
Knight knight1 = new Knight();
Knight knight2 = new Knight();
Console.WriteLine($"총 생성된 Knight 객체 수: {Knight.counter}");
Knight knight3 = Knight.CreateKnight();
}
}
4. static의 특징과 규칙
✅ static 변수
- 모든 인스턴스가 동일한 값을 공유하며, 단 하나만 존재함
- 객체 없이도 클래스 이름을 통해 접근 가능
- 객체마다 개별 값을 가지는 인스턴스 변수와 다름
✅ static 메서드
- 객체 없이 클래스 이름을 통해 직접 호출 가능
- static 변수만 접근 가능하며, 인스턴스 변수는 접근 불가
- 일반 멤버 변수에 접근하려면 별도로 객체를 생성해야 함
static public void Test()
{
this.hp = 100;
}
✅ static과 인스턴스 멤버 차이
- static 메서드에서는 일반 멤버 변수를 사용할 수 없음 (객체에 종속되지 않기 때문)
- 하지만 static 메서드에서 객체를 생성하여 사용할 수는 있음
static public Knight CreateKnight()
{
Knight knight = new Knight();
knight.hp = 100;
knight.attack = 10;
return knight;
}