Created
January 18, 2014 18:40
-
-
Save rajeevprasanna/8494434 to your computer and use it in GitHub Desktop.
Encapsulation examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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