Code:
public class MiscTest {
public static void main(String args[]){
Person p1 = new Person("person1");
Height p1_h = p1.getHeight();
p1_h.setInches(6);
Height p1_h2 = p1.getHeight();
System.out.println("Height = " + p1_h2.getFeet() +
"feet And " + p1_h2.getInches() +
" Inches");
}
}
class Person {
private String name;
private Height height;
public Person(String p_name){
name = p_name;
height = new Height(5, 11);
}
public Height getHeight(){ return height; }
}
class Height {
int feet;
int inches;
Height(int p_feet, int p_inches){
feet = p_feet;
inches = p_inches;
}
void setInches(int p_inches){
inches = p_inches;
}
int getInches(){ return inches;};
int getFeet(){ return feet;};
}
Here you go, inches should be "11" but they are now changed to "6" because:
Code:
Height p1_h = p1.getHeight();
p1_h.setInches(6);
broke the encapsulation and changed the value of a private data member.
This is so stupid!