특정한 영역에서 이름이 겹쳐서 다른 변수를 가리는 것을 섀도잉이라고 표현한다.
class Program
{
public static int number = 10;
static void Main(string[] args)
{
int number = 20;
Console.WriteLine(number);
}
}
//실행결과
//20
부모 클래스와 자식 클래스 사이에 동일한 이름으로 멤버를 만들거나 메서드를 정의할 때 하이딩이라고 부른다.
class Human
{
public void SayHello()
{
Console.WriteLine("hello");
}
}
class Teacher : Human
{
public void SayHello()
{
Console.WriteLine("hello, Student");
}
}
class Student : Human
{
public void SayHello()
{
Console.WriteLine("hello, Yo");
}
}
class Program
{
static void Main(string[] args)
{
Student student = new Student();
Teacher teacher = new Teacher();
student.SayHello();
teacher.SayHello();
}
}
class Human
{
public void SayHello()
{
Console.WriteLine("hello");
}
}
class Teacher : Human
{
public new void SayHello()
{
Console.WriteLine("hello, Student");
}
}
class Student : Human
{
public new void SayHello()
{
Console.WriteLine("hello, Yo");
}
}
class Program
{
static void Main(string[] args)
{
Student student = new Student();
Teacher teacher = new Teacher();
student.SayHello();
teacher.SayHello();
}
}
오버라이딩은 부모 클래스의 메서드를 자식 클래스에서 재정의하는 것을 의미한다.
class Human
{
public virtual void SayHello()
{
Console.WriteLine("hello");
}
}
class Teacher : Human
{
public override void SayHello() //오버라이딩을 하려면 override
{
Console.WriteLine("hello, Student");
}
}
class Student : Human
{
public override void SayHello() //오버라이딩을 하려면 override
{
Console.WriteLine("hello, Yo");
}
}
class Program
{
static void Main(string[] args)
{
Student student = new Student();
Teacher teacher = new Teacher();
teacher.SayHello();
student.SayHello();
}
}
//출력결과
hello, Student
hello, Yo
아래와 같은 코드를 살펴보자
class Human
{
public void SayHello()
{
Console.WriteLine("hello");
}
}
class Teacher : Human
{
public new void SayHello()
{
Console.WriteLine("hello, Student");
}
}
class Student : Human
{
public new void SayHello()
{
Console.WriteLine("hello, Yo");
}
}
class Program
{
static void ClassRoom(Human human)
{
human.SayHello();
}
static void Main(string[] args)
{
Student student = new Student();
Teacher teacher = new Teacher();
ClassRoom(student);
ClassRoom(teacher);
}
}
//출력결과
//hello
//hello
class Human
{
public virtual void SayHello()
{
Console.WriteLine("hello");
}
}
class Teacher : Human
{
public override void SayHello()
{
Console.WriteLine("hello, Student");
}
}
class Student : Human
{
public override void SayHello()
{
Console.WriteLine("hello, Yo");
}
}
class Program
{
static void ClassRoom(Human human)
{
human.SayHello();
}
static void Main(string[] args)
{
Student student = new Student();
Teacher teacher = new Teacher();
ClassRoom(student);
ClassRoom(teacher);
}
}
//출력결과
//hello, Yo
//hello, Student
메서드 오버라이딩으로 메서드를 재정의하면 상속된 부모의 메서드를 호출하더라도 부모의 원래 메서드가 나타나는 것이 아니라 자식의 메서드가 부모의 메서드를 완전히 덮어씌워 부모의 메서드를 호출하더라도 재정의된 자식들이 가지고 있는 메서드 값이 출력된다.
하이딩을 단독으로 사용할 경우는 잘 없다 메서드 오버라이딩의 개념을 명확히 이해하자