Menu

Monday, June 17, 2013

[C#] ความแตกต่างระหว่างเมธอดที่ใช้ new กับ override
[C#] What Different between new and override Method

override - เมธอดของคลาสแม่ถูกเขียนทับในคลาสลูก
override - a method of a base class is overridden in a derived class

new - เมธอดของคลาสแม่ถูกซ่อนเอาไว้จากคลาสลูก โดยการประกาศเมธอดที่เหมือนกับคลาสแม่ในคลาสลูก
new - a method of a base class is hidden in a derived class by defining the same method of a base class in a derived class

ถ้าไม่ได้กำหนดคีย์เวิร์ดว่าเป็น override หรือ new ค่าตั้งต้นจะเป็น new
If you do not specify either override or new keyword, the default keyword is new

สำหรับตัวอย่าง ประกาศคลาสตามด้านล่าง
For example, define classes as follow
  1. class A
  2. {
  3.      public virtual void print()
  4.      {
  5.           Console.WriteLine("This is A");
  6.      }
  7. }
  8. class B : A
  9. {
  10.      public override void print()
  11.      {
  12.           Console.WriteLine("This is B");
  13.      }
  14. }
  15. class C : A
  16. {
  17.      public new void print()
  18.      {
  19.           Console.WriteLine("This is C");
  20.      }
  21. }

ในเมธอด main, ใส่โค้ดตามด้านล่าง แล้วคอมไพล์และรัน
In main method, add the code below then compile and run
  1. A a = new A();
  2. B b = new B();
  3. C c = new C();
  4. a.print();
  5. b.print();
  6. c.print();

ผลลัพธ์ที่ได้ คือ
The output is 
This is A
This is B
This is C

นี่เป็นเพราะเมธอด print ของแต่ละคลาสถูกเรียก
This is because print method of each class is called

ในเมธอด main, เปลี่ยนโค้ดตามด้านล่าง แล้วคอมไพล์และรัน
In main method, change the code as follow then compile and run 
  1. A[] a = new A[3];
  2. a[0] = new A();
  3. a[1] = new B();
  4. a[2] = new C();
  5. for (int i = 0; i < 3; i++)
  6.      a[i].print();

ผลลัพธ์ที่ได้ คือ
The output is
This is A
This is B
This is A

นี่เป็นเพราะเมธอด print ของคลาส A ถูกเรียกจากคลาสลูก
This is because print method of class A is called from inherited class

สำหรับคลาส B, เมธอด print ของคลาส A ถูกเขียนทับในคลาส B ดังนั้นเมธอด print ของคลาส B จึงถูกเรียกแทน
For class B, print method of class A is overridden by class B so print method of class B is called instead

สำหรับคลาส C, เมธอด print ของคลาส A ถูกเรียก เพราะเมธอด print ของคลาส C เป็นเมธอดที่นิยามขึ้นมาใหม่ ซึ่งไม่มีส่วนเกี่ยวข้องกับคลาส A เลย
For class C, print method of class A is called because print method of class C is new defined method that is not related to class A

No comments:

Post a Comment