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.
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.
0 comments: