Skip to content

Instantly share code, notes, and snippets.

@rajeevprasanna
Created January 18, 2014 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajeevprasanna/8494434 to your computer and use it in GitHub Desktop.
Save rajeevprasanna/8494434 to your computer and use it in GitHub Desktop.
Encapsulation examples
package encapsulation;
public class EncapsulationExample {
public int left = 9;
public int right = 3;
// Now consider this question: Is the value of right always going to be one-
// third the value of left? It looks like it will, until you realize that
// users of the Foo class don’t need to use the setLeft() method! They can
// simply go straight to the instance variables and change them to any
// arbitrary int value.
public void setLeft(int leftNum) {
left = leftNum;
right = leftNum / 3;
}
// lots of complex test code here
}
package encapsulation;
public class EncapsulationTest2 {
private String name;
private String idNum;
private int age;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getIdNum() {
return idNum;
}
public void setAge(int newAge) {
age = newAge;
}
public void setName(String newName) {
name = newName;
}
public void setIdNum(String newId) {
idNum = newId;
}
}
package encapsulation;
public class Test2 {
public static void main(String args[]) {
EncapsulationTest2 encap = new EncapsulationTest2();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName() + " Age : "
+ encap.getAge());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment