Sunday 6 January 2013

Chapter 2: Object Orientation: Encapsulation

package net.dharmaraj.scjp;

public class BadObjectOrentedProgramming
{
    public int size;
    public int weight;
}

class ExploitBadOO
{
    public static void main (String [] args) {
        BadObjectOrentedProgramming b = new BadObjectOrentedProgramming();
        b.size = -5;                 // Legal but bad!!
        }
}



Keep instance variables protected (with an access modifier, often private).
n Make public accessor methods, and force calling code to use those methods
rather than directly accessing the instance variable.
n For the methods, use the JavaBeans naming convention of
set<someProperty> and get<someProperty>.




We call the access methods getters and setters although some prefer the fancier
terms accessors and mutators. (Personally, we don't like the word "mutate".)
Regardless of what you call them, they're methods that other programmers must go
through in order to access your instance variables. They look simple, and you've
probably been using them forever:








package net.dharmaraj.scjp;

public class Box
{
    // protect the instance variable; only an instance
    // of Box can access it " d " "dfdf"
    private int size;

    // Provide public getters and setters
    public int getSize()
    {
        return size;
    }

    public void setSize(int newSize)
    {
        size = newSize;
    }
}

No comments:

Post a Comment