Beginning Programming with Java For Dummies
Book image
Explore Book Buy On Amazon

One of the issues that tends to confuse many new Java developers (and some experienced Java developers as well), is the concept of properties in Java. Some languages have a formal mechanism for working with properties, but Java doesn’t provide this mechanism.

In addition, there’s some level of confusion about the terminology that Java uses for specific program elements that are related to properties. This section uses a specific set of terms that reflect the terminology used by the majority of Java developers, but you should expect to see other usages as you look around online.

A property is a value that you can access as part of the class or the object created from the class. You use properties to provide access to a global variable, which is also called a field.

The best practice is to always make fields private and then rely on special getter and setter methods to access them. The combination of field, getter, and setter is a property in Java. Here’s a typical example that uses an int named MyInt.

// Create the MyInt field.
private int MyInt = 0;
// Obtain the current value of MyInt.
public int getMyInt()
{
   return MyInt;
}
// Set a new value for MyInt.
public void setMyInt(int MyInt)
{
   this.MyInt = MyInt;
}

In this example, the code declares a private variable, MyInt, and assigns it a value of 0. The getter, getMyInt(), provides the current value of MyInt to the caller, while the setter, setMyInt(), lets the caller change the value of MyInt.

The reason you want to use properties is so that you have better control over how a caller interacts with MyInt. By using setters and getters, you make it possible to do tasks such as verify the range of values that a caller provides and then throw an exception when the input is incorrect in some way.

A field is a kind of global variable that holds data that the class or object manages. Some developers extend the term field to include all sorts of other meanings, but this book uses field to specifically mean a globally accessible variable.

Getters and setters are special methods that provide access to fields. Using getters and setters helps you control field access and reduces the chance that the field will be used incorrectly.

To protect a field from damage, such as receiving incorrect data values, you must declare it as private and rely on getters and setters to access it. The getters and setters must provide any checks required to ensure the caller interacts with the private field correctly.

About This Article

This article can be found in the category: