Classes and objects are one of the key attributes in object-oriented programming (OOP). The general relation between the two can be described as “is-a”: a class describes a template for objects, while an object is a specific instance of a class (Farrell, 2014). The primary concept of this relationship is reusability — code written for a class allows multiple different objects to be instantiated from it (Farrell, 2014). Another important concept is implementation hiding, meaning that the specific implementation of a method within a class is irrelevant to its user, as long as the arguments and return types are consistent (Farrell, 2014). For example, the particular implementation of an item being added to and retrieved from a database can change, but parts of the program handling these actions do not need to be updated because the methods inputs and outputs remain unchanged. Methods are blocks of code within classes that combine instructions that can be called repeatedly (Farrell, 2014). In banking software, a method of a hypothetical Account class can be used to update its credit score based on the Account’s properties. Static fields are fields shared by all instances of a class (Farrell, 2014). These are useful for variables holding information such as the number of objects of a given class currently instantiated, or variables that are used by all these objects.
A constructor is a special method used to establish an object. Java provides a default constructor for objects that sets default values to the object’s data fields (Farrell, 2014). One can create a custom constructor that receives parameters, which are often used to initialize an object’s data fields (Farrell, 2014). This is another feature of OOP that improves the reusability and clarity of code by allowing an object with specific fields to be instantiated in one line. Constructors, like other methods, can be overloaded, that is, multiple constructors can be written for the same class that receives different parameters (Farrell, 2014). This feature allows one to establish default values for his or her objects’ fields. For instance, a database application that stores information on people can substitute “Anonymous” if a name is not provided.
Reference
Farrell, J. (2014). Java Programming (7th ed.). Boston, MA: Cengage Learning.