Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects. An object has a unique identity, state, and behaviors.
The state of an object is represented by data fields (also known as properties ) with their current values.
The behavior of an object is defined by a set of methods . Invoking a method on an object means that you ask the object to perform a task.
A circle object, for example, has a data field, radius , which is the property that characterizes a circle. One behavior of a circle is that its area can be computed using the method getArea() .
Objects of the same type are defined using a common class. A class is a template or blueprint that defines what an object's data and methods will be. An object is an instance of a class. You can create many instances of a class. Creating an instance is referred to as instantiation . The terms object and instance are often interchangeable. The relationship between classes and objects is analogous to the relationship between apple pie recipes and apple pies. You can make as many apple pies as you want from a single recipe. Figure 7.1 shows a class named Circle and its three objects.
A Java class uses variables to define data fields and methods to define behaviors. Additionally, a class provides methods of a special type, known as constructors , which are invoked when a new object is created. A constructor is a special kind of method. A constructor can perform any action, but constructors are designed to perform initializing actions, such as initializing the data fields of objects. Figure 7.2 shows an example of the class for Circle objects.
The Circle class is different from all of the other classes you have seen thus far. It does not have a main method and therefore cannot be run; it is merely a definition used to declare and create Circle objects. For convenience, the class that contains the main method will be referred to as the main class in this book.
The illustration of class templates and objects in Figure 7.1 can be standardized using UML ( Unified Modeling Language ) notations. This notation, as shown in Figure 7.3, is called a UML class diagram , or simply a class diagram . For more information on UML, see www.rational.com/uml/.
In the class diagram, the data field is denoted as
dataFieldName: dataFieldType
The constructor is denoted as
ClassName(parameterName: parameterType)
The method is denoted as
methodName(parameterName: parameterType): returnType