Sufficiency Economy
Group Blog
 
All blogs
 
LOVE JAVA : Day5 ทดสอบคุณสมบัติ Shadowing และ Overriding

หน้า 207

ถ้าเราขยาย class แล้วสร้าง data member หรือ method ที่เหมือน class แม่

เวลาที่เราสร้าง instance ก็จะงงว่าแล้วจะเรียกใช้ data member หรือ method จาก class ใด

แต่ ระบบ ได้กำหนดแล้วว่า ให้เกิดการบัง(shadow) data member ของ class แม่ หรือ

ครอบงำ(override) method ของ class แม่

<ในภาษา C++ ใช้คำว่า override คำเดียว>

<ถ้ามีคำว่า final นำหน้า data member หรือ method > เราจะไม่สามารถ shadow หรือ override ได้เน้อ>

ประโยชน์ในหนังสือบอกว่า ถ้ามี class ที่มีคุณสมบัติที่เราต้องการอยู่แล้ว แต่บาง method ไม่เหมาะสม เราก็จะ override method นั้นใหม่

ตัวอย่าง code แรกคือการ บัง data member ที่ชื่อว่า x 

ดังนั้นเวลาเรียก จึงแสดงค่า x ของ class  B แทน   

class A {int x = 1;}
class B extends A {float x = 2.0f;}
class Shadowing
{
 public static void main(String args[])
 {
  B b = new B();
  System.out.println(b.x);
 }
}

ส่วนตัวอย่างนี้ เป็นการ ครอบงำ(override) method ที่ชื่อว่า print

ทำให้เวลาเรียกใช้ จึงแสดงตัวอักษร B แทน

class A
{ void print()
 {
  System.out.println('A');
 }
}

class B extends A
{
 void print()
 {
  System.out.println('B');
 }
}

class Overriding
{
 public static void main(String args[])
 {
  new B().print();
 }
}

วันนี้ห้าแล้ววว เมื่อไรจะรู้เรื่องเนี่ยยยย




Create Date : 30 พฤษภาคม 2557
Last Update : 30 พฤษภาคม 2557 19:38:39 น. 0 comments
Counter : 1473 Pageviews.

ชื่อ :
Comment :
  *ใช้ code html ตกแต่งข้อความได้เฉพาะสมาชิก
 

wink99_th
Location :
พิษณุโลก Thailand

[Profile ทั้งหมด]

ฝากข้อความหลังไมค์
Rss Feed
Smember
ผู้ติดตามบล็อก : 8 คน [?]




New Comments
Friends' blogs
[Add wink99_th's blog to your web]
Links
 

 Pantip.com | PantipMarket.com | Pantown.com | © 2004 BlogGang.com allrights reserved.