Friday, May 14, 2010

SCJP Exam Watch 4 - Encapsulation

Look out for code that appears to be asking about the behavior of a method, when the problem is actually a lack of encapsulation. Look at the following example, and see if you can figure out what's going on:

class Foo {
    public int left = 9;
    public int right = 3;

    public void setLeft(int leftNum) {
        left = leftNum;
        right = leftNum/3;
    }

    // lots of complex test code here
}

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! Thay can simply go straight to the instance variables and change them to any arbitrary int value.


Refrence: SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065)

No comments:

Post a Comment

Java, JavaScript, HTML, XHTML, AJAX, CSS, etc.