메서드를 만들 때 정적(static) 키워드를 사용하는 이유

[관련 Page : 159]

정적(static) 키워드로 선언한 메서드는 객체 인스턴스(instance)를 생성하지 않고도 호출이 가능하다.
정적 메서드가 아닌 메서드는 객체 인스턴스를 생성(new 인스턴스 이름)하면 힙(heap)이라는 메모리 공간 안에 객체가 생성되므로, 인스턴스를 생성할 때 마다 별도의 객체가 생성이 된다.
정적(static) 키워드를 사용하는 이유는, 값을 공유하기 위한 용도로 사용하기 위함이다. (참조페이지 : https://wikidocs.net/228)


[연습코드]

* static 메서드의 경우는 바로 호출이 가능하지만, non-static 메서드의 경우는 인스턴스를 생성해 주어야만 호출이 가능한 것을 알 수 있었다.

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

namespace StaticTest
{
    class Program
    {
        static void Main(string[] args)
        {
            StatTest.StatPrn();
            StatTest nonTest = new StatTest();
            nonTest.Prn();
            // StatTest.Prn(); 빨간 밑줄!
        }
    }

    class StatTest
    {
        public static void StatPrn()
        {
            Console.Out.Write("Static에서 작동하는 Method\n");
        }

        public void Prn()
        {
            Console.Out.Write("non-Static에서 작동하는 Method\n");
        }
    }
}


  Comments,     Trackbacks