Instance vs Static Method

Static Method (일면 Class Method)
-메서드 선언에 static 한정자가 있는 경우 해당 메서드를 정적 메서드라고 한다.
-정적 메서드는 class method나 static member field 조작을 위한 메소드이다.
-정적 메서드 내에서 클래스의 instance field나 method는 접근 불가능하다.
-정적 메서드는 특정 인스턴스에서는 작동되지 않으므로, 정적 메서드 내에서 this를 참조하면 컴파일 타임 오류가 발생한다.

Instance Method
-인스턴스 메서드는 클래스의 지정된 인스턴스에서 작동한다.
-인스턴스 메서드 내에서는 this로 액세스할 수 있다.

class ValueClass
{
private int value = 0;
public void setValue(int value) { this.value = value; }
public int getValue() { return this.value; }
public void print() { Console.WriteLine(“value={0}”, this.value);
public static void printString(string str) { Console.WriteLine(str); }
}
class Program
{
static void main(string[] args)
{
ValueClass c = new ValueClass();
c.setValue(10); // 인스턴스 메소드
c.print(); // 인스턴스 메소드
ValueClass.printString(“test”); // 정적 메소드 (클래스명.정적메소드명)
}
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *