상속?

캡슐화 및 다형성과 함께 객체 지향 프로그래밍의

세가지 주요 특성 중 하나

다른 클래스에 정의된 동작을 재사용, 확장 및 수정하는 새 클래스를 만들 수 있다.

 

사용하는 이유?

코드 기능을 재사용, 구현 시간 단축

 

맴버가 상속되는 클래스를 기본 클래스

해당 맴버를 참조하는 클래스를 파생클래스

https://www.youtube.com/watch?v=SiAyDvab-wc&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=37

 

 

단 , 부모가 둘일 수는 없다.

 

새 클래스를 만들 때 기존 클래스의 필드와 메서드를 재사용

 

=> 더 쉽게 만들고 유지 관리할 수 있다

 

 

protected 접근제어자를 사용하는 주된 이유는,

 

해당 클래스나 상속받은 다른 클래스에서만 생성자를 호출할 수 있게 제한함으로써,

의도치 않은 인스턴스 생성을 방지하고 객체의 일관성을 유지하기 위해서

 

 

 

 

상속을 받았다면 부모 클래스의 생성자도 호출됨

 

 

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

namespace Step37
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Marine marineA = new Marine();
            marineA.Init("마린 A", 10);
            marineA.damage = 2;

            Marine marineB = new Marine();
            marineB.Init("마린 B", 10);
            marineB.damage = 2;

            Medic medic = new Medic();
            medic.healValue = 3;

            marineB.Attack(marineA);

            Console.WriteLine("마린 A의 체력 : {0}",marineA.GetHp());
            Console.WriteLine("마린 B의 체력 : {0}",marineB.GetHp());

            medic.Heal(marineA);

            Console.WriteLine("마린 A의 체력 : {0}", marineA.GetHp());
            Console.WriteLine("마린 B의 체력 : {0}", marineB.GetHp());
        }
    }
}

 

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

namespace Step37
{
    internal class TerranUnit : StarcraftUnit
    {
        protected int hp;
        protected int maxHp;

        public TerranUnit()
        {
            Console.WriteLine("TerranUnit 클래스 생성자");
        }

        public void Init(string name, int maxHp)
        {
            this.name = name;
            this.maxHp = maxHp;
            this.hp = this.maxHp;
        }

        public void Hit(int damage)
        {
            this.hp -= damage;
            Console.WriteLine("{0}이 피해{1}를 받았습니다", this.name, damage);
        }

        public int GetHp()
        {
            return this.hp;
        }

        public void AddHp(int heal)
        {
            this.hp += heal;

            Console.WriteLine("{0}의 체력이 회복 되었습니다", this.name);

            if(this.hp >= this.maxHp)
            {
                this.hp = this.maxHp;
            }
        }
    }
}

 

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

namespace Step37
{
    internal class StarcraftUnit
    {
        public string name;
        //생성자
        public StarcraftUnit()
        {
            Console.WriteLine("StarcraftUnit 생성자");
        }
    }
}

 

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

namespace Step37
{
    internal class Marine : TerranUnit
    {
        public int damage;
        public Marine()
        {
            Console.WriteLine("Marine 클래스 생성자");

        }

        public void Attack(TerranUnit target)
        {
            target.Hit(this.damage);
        }

    }
}

 

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

namespace Step37
{
    internal class Medic : TerranUnit
    {
        public int healValue;
        public Medic()
        {
            Console.WriteLine("Medic 클래스 생성자");
        }

        public void Heal(TerranUnit target)
        {
            target.AddHp(this.healValue);
        }
    }
}

 

'Study > C#' 카테고리의 다른 글

[C#] 생성자 연결  (0) 2024.06.12
[C#] virtual, override  (0) 2024.06.12
[C#] static 한정자  (0) 2024.06.02
[C#] this 키워드  (0) 2024.05.31
[C#] 점연산자 NullReferenceException  (0) 2024.05.30

메서드 오버로딩?

다형성을 구현하는 방법중 하나

즉, 하나 이상의 형태를 취할 수 있는 능력

https://www.youtube.com/watch?v=UQmok_QRSKY&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=36

 

 

메서드 오버로딩은

동일한 이름을 가진 여러 메서드를 정의하는 것

 

메서드 오버로딩을 사용하는 때

 

1. 매개변수의 수 변경

2. 다른 타입의 매개변수 사용

3. 서로 다른 타입의 매개변수 순서 변경

 

 

 

생성자 오버로딩

 

 

 

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

namespace Step36
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Calculator calc = new Calculator();
            //int result = calc.Add(1, 2);
            //Console.WriteLine(result);

            //result = calc.Add(1, 2, 3);
            //Console.WriteLine(result);

            //calc.Subtract(1.3f, 1.5f);
            //calc.Subtract(5, 1.5f);
            //calc.Subtract(10f, 5);

            //calc.Multiple(1.5f, 2);
            //calc.Multiple(2, 1.5f);
            
            //생성자 오버로딩
            Hero hong = new Hero();
            Hero lim = new Hero("임꺽정");
            Hero jang = new Hero("장길산", 3, 10);
            
        }
    }
}

 

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

namespace Step36
{
    internal class Calculator
    {
        //클래스가 생성되면 기본 생성자를 만들자

        public Calculator()
        {

        }

        //메서드 오버로딩
        public int Add(int a, int b)
        {
            int result = a + b;
            return result;
        }
        //다른 매개변수의 수
        public int Add(int a, int b, int c)
        {
            int result = a + b + c;
            return result;
        }

        public int Subtract(int a, int b)
        {
            int result = a - b;
            return result;
        }
        //다른 타입의 매개변수
        public int Subtract(float a, float b)
        {
            int result = Convert.ToInt32(a - b);
            return result;
        }

        public int Subtract(int a, float b)
        {
            int result = a - (int)b;
            return result;
        }
        //서로다른 매개변수의 순서 변경
        public int Multiple(int a, float b)
        {
            int result = a * (int)b;
            return result;
        }

        public int Multiple(float a, int b)
        {
            int result = (int)a * b;
            return result;
        }
        
        //반환타입이 다른것은 오버로딩 불가능

    }
}

 

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

namespace Step36
{
    internal class Hero
    {
        //생성자
        public Hero()
        {
            Console.WriteLine("매개변수가 없는 기본 생성자");
        }

        //생성자 오버로딩
        public Hero(string anme)
        {
            Console.WriteLine("매개변수가 1개 있는 생성자");

        }

        //생성자 오버로딩
        public Hero(string name, int damage, int maxHp)
        {
            Console.WriteLine("매개변수가 3개 있는 생성자");

        }
    }
}

'낙서장 > C#' 카테고리의 다른 글

virtual ,override, base  (2) 2024.03.08
상속과 다형성  (1) 2024.03.08
흐름 제어  (1) 2024.02.26
데이터를 가공하는 연산자  (0) 2024.02.25
데이터를 담는 변수와 상수  (0) 2024.02.22

+ Recent posts