[C#] 클래스 상속

Young·2024년 5월 28일
1

C#

목록 보기
5/9
using System;
using System.Threading.Channels;

namespace thisIsCSharp
{
    class GrandParents
    {
        public void Family()
        {
            Console.WriteLine("Family : La Familia Madrigal");
        }
    }

    class Parents : GrandParents
    {
        public void Home()
        {
            Console.WriteLine("Home : Casita");
        }
    }

    class Child : Parents
    {
        public void Age(int _Age)
        {
            Console.WriteLine("Age : "+_Age);
        }
    }

    class MainApp
    {
        static void Main(string[] args)
        {
            Child Mirabel = new Child();
            Console.WriteLine("\n미라벨!");
            Mirabel.Family();
            Mirabel.Home();
            Mirabel.Age(15);

            GrandParents Alma = new GrandParents();
            Console.WriteLine("\n할머니!");
            Alma.Family();

            Parents Julieta = new Parents();
            Console.WriteLine("\n엄마 훌리에타!");
            Julieta.Family();
            Julieta.Home();

            Parents Bruno = (Parents)Mirabel;       // 자식은 부모한테 넣을 수 있다.
            Console.WriteLine("\n브루노 삼촌!");
            Bruno.Family();
            Bruno.Home();

            //Child Isabela = (Child)Julieta;       // 부모는 자식한테 넣을 수 없어
            //Console.WriteLine("\n이사벨라 언니!");
            //Isabela.Family();
            //Isabela.Home();
            //Isabela.Age(17);
        }
    }
}


부모를 자식에게 넣으면 이런 식으로 오류가 뜬다. (주석처리한 부분)


실제 결과

상속에서 기억할 것

  1. 자식은 부모의 데이터에 접근할 수 있지만 부모는 자식의 데이터에 접근할 수 없다.

  2. 아무리 자식이라도 부모의 private 데이터에는 접근할 수 없다.

  3. 대분류 - 중분류 - 소분류 개념

profile
Beginner : C#

0개의 댓글