본문 바로가기
유니티

6/30 C# 클래스 상속

by SUGI_ 2023. 6. 30.

클래스에는 다른 클래스의 멤버를 받아 이어받는 기능이 있다.

namespace Class상속
{
    class Book
    {
        public string title;
        public string genre;

        public void printBook()
        {
            Console.WriteLine("분야 : " + genre);
        }
    }

    class Novel : Book
    {
        public string writer;
        public void printNov()
        {
            printBook(); //부모함수 호출
            Console.WriteLine("저자 : " + writer);
        }
    }

    class Magazin : Book
    {
        public int day;
        public void printMag()
        {
            printBook();
            Console.WriteLine("발 매 일 : " + day + "일");
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            //클래스를 만들어서 사용하려고 하면 객체화 한다.
            Novel novel = new Novel();
            novel.title = "미희의 비경 발견";
            novel.genre = "판타지";
            novel.writer = "앤크";

            Magazin mag = new Magazin();
            mag.title = "월간 C# 그림책";
            mag.genre = "컴퓨터";
            mag.day = 20;

            novel.printNov();
            Console.WriteLine();
        }
    }
}

상속한 멤버의 접근 제한

public 다사용가능

private 나만사용가능

protected 상속인사람까지만 사용가능

namespace 상속접근제어
{
    class A
    {
        protected int a = 7; //public 키워드 변수
    }

    class B : A
    {
        public void Calc()
        {
            int x = 3 + a; //a변수 사용가능 public 
            Console.WriteLine(x);
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            //호출하고 싶은 것을 객체화 시킨다
            B b = new B(); //객체로 만든다.

            b.Calc();
        }
    }
}

Sealed ('실드') 상속되지 않도록 할 클래스

Static 필드 메소드에 붙여서 쓸 수 있다. / 정적인 이라는 의미

class A
{
	public static int a;
}
// 할당 메모리준다. 객체화한다
A.a = 10;

너무 낭비하면 메모리 차지가 너무 심함. 필요할 때 사용하도록!

namespace Static키워드
{
    class Purse
    {
        public static int money = 0; //static 0 실행되는동안 값이 유지가 된다. //공통의 변수

        public void printMoney(int In, int Out)
        {
            money = money + In - Out;

            if (money < 0)
            {
                Console.WriteLine((-1 * money) + "원 부족합니다.");
            }
            else
            {
                Console.WriteLine("잔액은 " + money + "원입니다.");
            }
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            Purse store1 = new Purse(); //객체화해서 사용
            Purse store2 = new Purse(); //객체2
            store1.printMoney(1000, 100); //900

            // 공용이 되기때문에 900원에서 250을 빼게 됨 //650
            store2.printMoney(0, 250);
            store1.printMoney(0, 800); //150부족
            Purse.money = 1000;
            Console.WriteLine("돈 :" + Purse.money);
        }
    }
}

 

[문제]

728x90