c# ☃️

[C#] Class 정의/예제/사용법 - OOP

소로리 산적 2024. 5. 6. 04:59

Class

🥕A class is a blue print of an Object
🥕It has actions/abilites - so called member functions or methods
🥕And it has properties - so called member variables
🥕Inheritance possible
🥕Can be used like a Datatype



구성



👊기본예제

Program.cs

namespace Class1;
class Program
{
    static void Main(string[] args)
    {
        // 새 키워드는 새 인스턴스를 생성하는데 사용
        // new 를 쓰면 새 객체를 위해 새 메모리 힙에 할당 
        Car honda = new Car();
    }
}


Car.cs

using System;
namespace Class1
{
	public class Car
	{
		public Car()
		{
			Console.WriteLine("Car 클래스 !");
		}
	}
}


실행결과



👊 살붙인 예제

Program.cs

namespace Class1;
class Program
{
    static void Main(string[] args)
    {
        // 새 키워드는 새 인스턴스를 생성하는데 사용
        // new 를 쓰면 새 객체를 위해 새 메모리 힙에 할당 
        Car honda = new Car();

        //Drive 호출 
        honda.Drive();

        Console.WriteLine("차를 멈추고 싶다면 1을 입력하시오 ;) ");
        string userInput = Console.ReadLine();

        if(userInput == "1")
        {
            honda.Stop();
        }
        else
        {
            Console.WriteLine("차는 아직 달리고 있다구 ~ ");
        }
    }
}


Car.cs

using System;
namespace Class1
{
	public class Car
	{
		public Car()
		{
			Console.WriteLine("Car 클래스 !");
		}

		public void Drive()
		{
			Console.WriteLine("운전중 =333");
		}

		public void Stop()
		{
			Console.WriteLine("멈춤 'ㅅ'");
		}
	}
}


실행결과