'오버라이딩'에 해당되는 글 1건

  1. 2009.05.31 [C#] 오버로딩과 오버라이딩

[C#] 오버로딩과 오버라이딩

Programming/.NET Programming 2009. 5. 31. 06:57

오버로딩과 오버라이딩 용어 정리

오버로딩 : 함수의 이름과 목적은 같지만, 구현 방법 등이 다를 경우, 파라미터의 타입이나 갯수의 차이로 함수를 구별하는 방식. 반환 타입으로는 구별되지 않는다.
ex. Console.WriteLine(); : 19개의 overloading 함수가 존재한다.

오버라이딩 : 함수가 같은 이름, 같은 타입, 같은 수의 매개변수를 가져도 다른(추가적) 기능을 구현하길 원할 때 사용하는 방식. 접근 제한 키워드와 함수 반환 타입 사이에 new를 적어주면 된다.
cf. override : 추상클래스로부터 상속을 받았을 때, 선언만 되어있는 함수를 구할 때 사용하는 키워드

오버로딩 예제(생성자 오버로딩)

using System;

namespace
Overloading

{

    public class TestA

     {

         public int a;

 

         public TestA()

         {

             Console.WriteLine("기본 생성자 입니다.");

         }

 

         /// <summary>

         /// 생성자 오버로딩

         /// </summary>
        
public TestA(int a)

         {

             a = 1;

             Console.WriteLine("오버로딩 생성자 입니다. a값은 " +a+"입니다.");

         }

 

         public static void Main(string[] args)

         {

             TestA A = new TestA();

             TestA B = new TestA(1);

         }

    }

}


오버라이딩 예제

using System;

 

namespace Overriding

{

    class Shape

    {

        public void method()

        {

            Console.WriteLine("Shape method입니다.");

        }

    }

 

    class Rectangle : Shape

    {

        public new void method()

        {

            Console.WriteLine("Rectangle method입니다.");

        }

    }

   

    class Triangle : Shape

    {

        public new void method()

        {

            Console.WriteLine("Triangle method입니다.");

        }

    }

 

    class Circle : Shape

    {

        public new void method()

        {

            Console.WriteLine("Circle method입니다.");

            base.method(); // base 키워드를 이용해 부모클래스의 method를 호출

        }

    }

    class Output

    {

        public static void Main(string[] args)

        {

            Shape s = new Shape();

            s.method();

            Rectangle r = new Rectangle();

            r.method();

            Triangle t = new Triangle();

            t.method();

            Circle c = new Circle();

            c.method();

        }

    }

}



'Programming > .NET Programming' 카테고리의 다른 글

[C#] Enum과 배열  (0) 2009.05.31
[C#] this와 상속  (0) 2009.05.31
[C#] 상속과 sealed  (1) 2009.05.31
[C#] 인터페이스, 추상클래스, 클래스  (1) 2009.05.31
[C#] static과 new 그리고 property  (0) 2009.05.31
: