Enforcing rules is tough. Luckily for you, Java has a more elegant solution than many parents are faced with. You can use accessor methods to make your stubborn code follow your rules.

Here’s some code that hides the fields.

public class Account {

private String name;

private String address;

private double balance;

public void setName(String n) {

name = n;

}

public String getName() {

return name;

}

public void setAddress(String a) {

address = a;

}

public String getAddress() {

return address;

}

public void setBalance(double b) {

balance = b;

}

public double getBalance() {

return balance;

}

}

Go back and take a quick look at the setName method. Imagine putting the method’s assignment statement inside an if statement.

public void setName(String n) {

<strong> if (!n.equals("")) {</strong>

name = n;

<strong> }</strong>

}

Now, if the programmer in charge of the UseAccount class writes myAccount.setName(""), the call to setName doesn’t have any effect. Furthermore, because the name field is private, the following statement is illegal in the UseAccount class:

myAccount.name = "";

Of course, a call such as myAccount.setName("Joe Schmoe") still works because "Joe Schmoe" doesn’t equal the empty string "".

That’s cool. With a private field and an accessor method, you can prevent someone from assigning the empty string to an account’s name field. With more elaborate if statements, you can enforce any rules you want.

About This Article

This article is from the book:

About the book author:

Dr. Barry Burd holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of Beginning Programming with Java For Dummies, Java for Android For Dummies, and Flutter For Dummies.

This article can be found in the category: