Information Hiding Revisited
This section discusses a subtle problem that can arise when defining certain kinds of classes. The problem does not apply to any class we define whose instance variables are either of a primitive type - such as int, double, char, and boolean - or of the type String. So we can define lots of classes without being concerned with this problem.
Privacy Leaks
A class can have instance variables of any type, including any class type. These often can be natural and useful things to have. However, using instance variables of a class type can introduce a problem that requires special care. The problem occurs because variables of a class type contain the memory address of the location where an object is stored in memory.
Example :
suppose that goodGuy and badGuy are both variables of the class type Pet. Now suppose that goodGuy names some object and our program executes the following assignment statement :
badGuy = goodGuy;
After this assignment statement is executed, badGuy and goodGuy are two names for the same objects. So if we change badGuy, we will also change goodGuy.
Let's give this assignment statement a bit more context to see its implication :
Pet goodGuy = new Pet ();
goodGuy.set("Faith Guard Dog", 5, 75);
Pet badGuy = goodGuy;
badGuy.set("Dominion Spy", 1200, 500);
goodGuy.writeOutput():
Because badGuy and goodGuy name the same object, this code will produce the following output :
Name : Dominion Spy
Age : 1200 years
Weight : 500.0 pounds
The change to badGuy also changed goodGuy because goodGuy and badGuy name the same object.
การซ่อนสารสนเทศมาเยือน
ส่วนนี้กล่าวถึงปัญหาที่ลึกซึ้งที่สามารถเกิดขึ้นเมื่อกำหนดบางชนิดของชั้นเรียน ปัญหาไม่ใช้ระดับใด เรากำหนดตัวแปรที่มีอินสแตนซ์มีทั้งประเภท - ดั้งเดิมเช่น int , char , คู่ , บูลีน - หรือประเภทของสตริง ดังนั้นเราสามารถกําหนดจํานวนชั้นเรียนโดยไม่ต้องเป็นกังวลกับปัญหานี้ .
การรั่วไหลของความเป็นส่วนตัวชั้นสามารถมีตัวอย่างตัวแปรของชนิดใด ๆรวมทั้งห้องประเภทใด เหล่านี้มักจะสามารถธรรมชาติที่มีประโยชน์และสิ่งที่ต้องมี อย่างไรก็ตาม การใช้อินสแตนซ์ของชนิดตัวแปรคลาสสามารถแนะนำปัญหาที่ต้องการการดูแลพิเศษ ปัญหานี้เกิดขึ้นเนื่องจากตัวแปรประเภทของชั้นเรียนประกอบด้วยหน่วยความจำที่อยู่ของสถานที่ที่วัตถุจะถูกเก็บไว้ในหน่วยความจำ เช่น
:สมมติว่ากู๊ดกาย แบดกายทั้งสองตัวแปรและประเภทของห้องสัตว์เลี้ยง ตอนนี้สมมติว่ากู๊ดกายชื่อวัตถุบางอย่างและโปรแกรมของเราดำเนินการต่อไปนี้กำหนดงบ :
กู๊ดกาย แบดกาย = ;
หลังจากงานนี้ เป็นงบดำเนินการ แบดกายกู๊ดกายเป็นสองชื่อและวัตถุเดียวกัน ดังนั้น ถ้าเราเปลี่ยน แบดกาย เราก็จะเปลี่ยน
กู๊ดกาย .ให้งบงานนี้เป็นบิตเพิ่มเติมบริบทเพื่อดูความหมาย :
กู๊ดกายสัตว์เลี้ยงสัตว์เลี้ยงใหม่ = ( ) ;
กู๊ดกายตั้ง ( ศรัทธา " หมา " , 5 , 75 ) ;
กู๊ดกายสัตว์เลี้ยง แบดกาย = ; แบดกาย ชุด ( " อำนาจ " สายลับ , 1200 , 500 ) ;
กู๊ดกาย . writeoutput() :
เพราะ แบดกาย และกู๊ดกายชื่อวัตถุเดียวกัน รหัสนี้จะผลิตออกต่อไปนี้ : ชื่อ
: การปกครองสายลับ
อายุ 1200 ปี
500.0 น้ำหนัก : ปอนด์การเปลี่ยนแปลง แบดกายยังเปลี่ยนกู๊ดกายเพราะกู๊ดกาย แบดกายชื่อและวัตถุเดียวกัน
การแปล กรุณารอสักครู่..
