[C# 2.0] static class

eunjin lee·2022년 9월 12일
0

C# 9.0 프로그래밍

목록 보기
26/50

static class는 오직 static 멤버 변수/메서드만을 가질 수 있다.


객체에 따른 데이터 저장이 별도로 없이 기능 구현만을 하기 위한 목적으로 클래스를 만들었을 경우, static class로 만들면 new 연산자로 인스턴스를 만들 필요 없이 해당 기능을 이용할 수 있는 이점이 있다.

System.Math가 대표적인 예이다.

✍ 샘플 코드

   class Test
    {
        static void Main(string[] args)
        {
            Earth.Rotate();
            Earth.Revolve();

            Console.WriteLine("Color of the Earth "+Earth.color);
            Console.WriteLine("Is the Earth round?"+Earth.isRound);
        }
     }
    
    static class Earth
    {
        public static string color = "Blue";
        public static bool isRound = true;

        public static void Rotate()
        {
            Console.WriteLine("In one day Earth makes one rotation on its axis.");
        }

        public static void Revolve()
        {
            Console.WriteLine("Earth is closer to the sun and revolves around it in about 365 days.");
        }
    }

✅ 결과

In one day Earth makes one rotation on its axis.
Earth is closer to the sun and revolves around it in about 365 days.
Color of the Earth Blue
Is the Earth round?True

🧐 더 알아보기

  • 위의 예제에서 Earth가 static class가 아니라 class 엿어도 인스턴스를 만들지 않고 Earth.color나 Earth.Rotate()를 사용할 수 있다.
  • class 자체를 static으로 선언해버리면, 이 클래스는 인스턴스 생성을 할 수 없고, 상속 관계를 이룰 수 없다.
  • 즉 기능 모음 성격의 class가 있을 때 이 기능을 오버라이드하여 사용자가 마음대로 변경하여 사용하기를 원하지 않을 경우 static class를 사용한다고 볼 수 있다.

0개의 댓글