๐ŸŽฎ Unity Study/C#

[C#][์ƒ์†๊ณผ ์ธํ„ฐํŽ˜์ด์Šค] virtual, abstract, interface

ibelieveinme 2023. 8. 19. 17:12
728x90

์ƒ์†๊ณผ ํด๋ž˜์Šค ์„ค๊ณ„ ์‹œ ํ”ํžˆ ์‚ฌ์šฉํ•˜๋Š” virtual, abstract, interface ๊ฐ€ ๋ฌด์—‡์ธ์ง€, ๋ฌด์Šจ ์ฐจ์ด๊ฐ€ ์žˆ๋Š”์ง€ ์•Œ์•„๋ณด์ž


virtual (ํ•จ์ˆ˜, ์†์„ฑ, ์ธ๋ฑ์„œ, ์ด๋ฒคํŠธ)

: ํŒŒ์ƒ ํด๋ž˜์Šค์—๊ฒŒ ์ƒ์†์œผ๋กœ ์™„๋ฒฝํ•œ ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜๋Š” ๊ฒƒ.

public class Animal(){
    public virtual void Speak(){
    	Console.WriteLine("");
    }
}

public class Dog : Animal(){
    public override void Speak(){
    	Console.WriteLine("๋ฉ๋ฉ");
    }
}

Dog maltize = new Dog();
maltize.Speak();

virtual ํ•œ์ •์ž๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ํ•จ์ˆ˜๋Š” ํŒŒ์ƒ ํด๋ž˜์Šค์—๊ฒŒ ์™„๋ฒฝํ•œ ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•  ์ˆ˜ ์žˆ๋‹ค. 

ํŒŒ์ƒ ํด๋ž˜์Šค์—์„œ override๋กœ ์žฌ์ •์˜ ํ•  ์ˆ˜ ์žˆ๊ณ  ํ•„์ˆ˜๋Š” ์•„๋‹ˆ๋‹ค.

์ฐธ๊ณ ) maltize.Speak()๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด ๋ถ€๋ชจ ํด๋ž˜์Šค๊ฐ€ ์•„๋‹Œ ์ž์‹ ํด๋ž˜์Šค๋งŒ ํ˜ธ์ถœ๋œ๋‹ค.(๋ฎ์–ด์”Œ์›Œ์ง)

 

abstract ( ํ•จ์ˆ˜, ์†์„ฑ, ์ธ๋ฑ์„œ, ์ด๋ฒคํŠธ, ํด๋ž˜์Šค )

: ํ˜•ํƒœ๊ฐ€ ๋ถˆ์™„์ „ํ•ด์„œ ํŒŒ์ƒ ํด๋ž˜์Šค์—์„œ override๋กœ ์žฌ๊ตฌํ˜„(ํ•„์ˆ˜)ํ•ด์•ผ ํ•œ๋‹ค.

: ์—ฌ๋Ÿฌ ํŒŒ์ƒ ํด๋ž˜์Šค์—์„œ ๊ณตํ†ต์ ์ธ ๊ธฐ๋Šฅ์„ ์ •์˜ํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

public abstract class Animal {
    public abstract void Speak();
}

public class Dog : Animal {
    public override void Speak(){
    	Console.WriteLine("๋ฉ๋ฉ");
    }
}

Dog maltize = new Dog();
maltize.Speak();

 

interface

: abstract์™€ ๋น„์Šทํ•˜์ง€๋งŒ ๋ฉค๋ฒ„๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค. Property๋Š” ์‚ฌ์šฉ๊ฐ€๋Šฅํ•˜๋‹ค.

public interface Animal(){
    void Speak();
    
    string Name { get; set; }
}

public class Dog : Animal {
    private string name;
    
    public void void Speak(){
    	Console.WriteLine(name + " ๋ฉ๋ฉ");
    }
    
    public string Name {
    	get{ return name; }
        set{ name = value; }
    }
}

Dog maltipoo = new Dog();
maltipoo.Name = "์€๋น„";
maltipoo.Speak();

์ƒ์†/์ถ”์ƒ ํด๋ž˜์Šค์™€ Interface์™€์˜ ์ฐจ์ด์ 

 

1) ์ƒ์†, ์ถ”์ƒ ํด๋ž˜์Šค๋Š” ํ•œ ๋ถ€๋ชจ ํด๋ž˜์Šค๋งŒ ์ƒ์†๋ฐ›์„ ์ˆ˜ ์žˆ์ง€๋งŒ, ์ธํ„ฐํŽ˜์ด์Šค๋Š” ์—ฌ๋Ÿฌ๊ฐœ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋‹ค.

But, ํด๋ž˜์Šค๊ฐ€ ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ฐ–๋Š” ๊ฒฝ์šฐ, ์ธํ„ฐํŽ˜์ด์Šค์˜ ๋ชจ๋“  ๋ฉค๋ฒ„๋ฅผ ๊ตฌํ˜„ํ•ด์•ผ ํ•œ๋‹ค.

 

2) abstract๋Š” ๊ฐœ๋…์ ์œผ๋กœ ๊ณ„์ธต์ ์ธ ๊ตฌ์กฐ(๋™๋ฌผ - ๊ฐ•์•„์ง€)์—์„œ ์‚ฌ์šฉ๋˜๋ฉฐ intercace๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ๊ณ„์ธต(์‚ฌ๋žŒ์ด๋‚˜ ๊ธฐ๊ณ„๊ฐ€ ๋ง์„ํ•˜๊ฒŒ(speak)ํ•˜๋Š” ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์ถ”๊ฐ€ํ•  ๋•Œ)์ด๋‚˜ ํƒ€์ž…์ด๋”๋ผ๋„ ๊ฐ™์€ ๊ธฐ๋Šฅ์„ ์ถ”๊ฐ€ํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

 

728x90

'๐ŸŽฎ Unity Study > C#' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[C#] Generic, Template  (0) 2023.08.21
[C#] ๋ฌธ๋ฒ• Keyword  (0) 2023.08.19
[C#][Unity] Event  (0) 2023.08.18
[C#] ? Question Mark  (0) 2023.08.18
[C#] C# ๋ฒ„์ „๋ณ„ ์ถ”๊ฐ€๊ธฐ๋Šฅ ์‚ฌํ•ญ, .NET & Visual Studio ๋ฒ„์ „  (0) 2023.08.18