Introduction to Objects


Object-Oriented Programming

The fundamental building block of the Java language is the class which is a template or pattern that describes the general structure and behavior of an abstract entity. Instance variables are used to store data values and class methods are used to define the operations that manipulate those data values.

An object is a specific instance of a class; an entity with the general behavior specified by the class methods but with its own specific data values. An object is created by invoking a special class method called a constructor which initializes the values of the class variables. Object-oriented programming is a programming style in which programs are composed primarily of interacting objects.

Methods and Method Parameters

Methods allow objects to interact with each other. In effect, a method represents a request made to an object. Some requests require a response. For example, we might request an object to tell us something about its current state. The corresponding method is said to return the requested value. In other cases, the request specifies some internal action to be taken by the object but requires no response. A method that returns no value is said to be void.

Methods often need additional data (in addition to the class variables) in order to carry out the request. These additional data values are referred to as parameters and are said to be passed to the method.

A method consists of a method declaration and a method body:

Method Diagram

The method declaration specifies the method access level (private or public), return type, name, and parameter list. The information in the method declaration is all a programmer needs to know in order to invoke the method and it is this information that is provided in the JavaDoc documentation. For example, here is the information we are given for the setText method of the JLabel class:

Method Declaration

The setText method is public which means that objects which use JLabel components (such as an applet) can invoke this method. A private method can only be invoked within the class itself. Private methods do not even appear in the JavaDoc documentation of a class.

The return type of the setText method is void. A void method, as noted above, does not return a value. In effect, setText carries out its task silently.

Finally, the setText method has only one parameter; an instance of the String class named "text". This parameter represents the text that is to be displayed in the JLabel component.

The method body is enclosed by braces and contains the Java statements that carry out the method's intended task. A programmer does not need to see the specific statements that implement a method in order to use the method. Consequently, the JavaDoc documentation only describes, in general terms, what the method does; not how it does it.

Method Parameters

A method may need some additional data in order to carry out its task. For example, consider the setText method of the JLabel class. In order to carry out its task, the new text must be passed to the  method as a parameter.

Formal Parameters

Within a method, the value of a parameter is associated with an identifier (just as a variable is associated with an identifier). Each of these identifiers is referred to as a formal parameter. The formal parameter identifiers are declared within the parentheses of the method declaration and each parameter declaration consists of the type of value followed by the formal identifier. The declarations are separated by commas:

(type formalId1, type formalId2, ..., type formalIdn)

If the method has no parameters, then there is nothing within the parentheses in the method declaration.

Actual Parameters

When a method is invoked, it must be supplied the values it needs to carry out its task. In the invocation, each value is referred to as an actual parameter or an argument. These values are listed within parentheses and separated by commas:

(actualParam1, actualParam2, ..., actualParamn)

If the method has no parameters, then there is nothing within the parentheses in the method invocation. The actual parameters can be literal values, constants, variables, value-returning method invocations, or expressions. In any case, the actual parameter must represent a value of the same type as the formal parameter.

There must be a one-to-one correspondence between the formal parameters listed in the method declaration and the actual parameters listed in the invocation. The value of the first actual parameter is assigned to the first formal parameter; the value of the second actual parameter is assigned to the second formal parameter; and so on. Each actual parameter and the corresponding formal parameter must be of the same type. The example below is the setText method of the JLabel class:

Method Declaration vs. Method Invocation

In summary, the formal parameters are the identifiers used in a method to store the values of the actual parameters listed in the method invocation.

Instance Methods vs. Class Methods

An instance method can be invoked only by an object. That is, you must construct an instance of the class before you can invoke an instance method. In general, an instance method manipulates one or more of the instance variables in the object that invokes the method. The setText method of the JLabel class is an example of an instance method. It changes the value of a JLabel object's text.

An instance method invocation includes the name of the object that is invoking the method, the name of the method, and the list of the actual parameters:

    objectName.methodName(actualParam1, actualParam2, ..., actualParamn);

Here is a specific example:

    lblMyName.setText("Del Searls");

A class method can be invoked directly by the class itself; no object is necessary. Class methods can access class variables but they cannot access instance variables. Since a class method cannot access instance variables, objects rarely invoke a class method (though they can).

The method declaration of a class method includes the word "static". Here is an example from the Math class:

Class Method

A class method invocation includes the name of the class, the name of the method, and the list of actual parameters:

    className.methodName(actualParam1, actualParam2, ..., actualParamn);

Here is a specific example:

    xComponent = Math.cos(Math.PI/4.0);

In this example, cos is a class method in the Math class that returns the cosine of its argument (which is an angle measured in radians). PI is a class constant in the Math class. The value returned by this method is the cosine of π/4 and will be assigned to the variable, xComponent.

See the methods quick reference page for summary information on methods.

The Class

A class consists of data elements, constructors, and methods. The data elements represent the information that is contained within an object of the given class. Typically, the data elements consist of instance variables. Less frequently, a class will also have class constants and class variables. Class constructors are used to create new objects with specific data values. Class methods comprise the interface between the object and its environment.

Class Data Elements

A class may declare several different types of data elements. A Class constant is a data element with a fixed value. The value of a class constant is specified in the constant declaration. The value of a class constant is stored only once in memory, no matter how many instances of the class are created.

A class variable is a data element whose value is subject to change. The value of a class variable is the same for every object of that class. Consequently, like a class constant, the value of a class variable is stored only once in memory, no matter how many instances of the class are created. Class variables are seldom needed.

An instance variable, like a class variable, is a data element whose value is subject to change. However, the value of an instance variable may be different for each object (each instance of the class). The values of the instance variables comprise the state of the object. Each object has its own set of values for these instance variables.

Declaring Class Data Elements

All data element declarations should include an access specifier, a type specifier, and an identifier. The access specifier determines whether the data element is private or public. A private data element can only be accessed from within the class itself. Typically, class and instance variables should be private. This protects the integrity of the object by preventing any outside entity from directly modifying its state. The only way to modify the state of an object should be through the invocation of a class method.

Public data elements can be accessed directly by an application or another object. In general, only class constants should be public and even then only if an application or another object would have a reasonable need to access them.

The type specifier indicates what type of value the data element represents. The type specifier can be a the name of a primitive data type (such as int or float) or the name of a class (such as JLabel).

The identifier is the name given to the data element and is used to access the value stored in the memory allocated to the data element. You should use meaningful identifiers (i.e., use wage rather than w). Identifiers normally consist of lowercase letters. If the identifier contains multiple words, the first letter of each word after the first is capitalized. Here are some examples:


In the table below, access indicates an access specifier (private or public), type indicates a type specifier (such as int, double, etc.), identifier indicates an identifier, and value indicates a specific value.  The static specifier indicates that the identifier represents a class constant or a class variable. The final specifier indicates that the identifier represents a constant rather than a variable.

Data Element Declaration Syntax
Class Constant final static access type identifier = value;
Class Variable static access type identifier;
Instance Variable access type identifier;
Local Variable type identifier

A local variable is a variable that is declared within the body of a class method. A local variable can be accessed only within the method in which it is declared. Typically, if a variable (or constant) is used in only one method, it should be declared as a local variable (or constant) within that method.

See the data declarations quick reference page for summary information on declaring data elements.

Class Constructors

In general, a constructor allocates memory for a new object and initializes the values of its instance variables. The default constructor has no parameters and creates a new object with default values for all of the instance variables. These default values are determined by the person who wrote the class definition. Every class should have a default constructor.

An initialization constructor has one or more parameters that are used to determine the initial values of the corresponding instance variables. This allows the application programmer to specify the initial values rather than using the default values specified by the class author. A class may define several initialization constructors; each having a different set of parameters. Since you can write class methods that allow the application programmer to change the value of an instance variable, initialization constructors are a convenience rather than a necessity.

A copy constructor has, as its only parameter, an object of the same class. It creates a new object with the same properties as its parameter. Like the initialization constructor, a copy constructor is a convenience rather than a necessity.

Defining Class Constructors

The general syntax for defining class constructors is given in the table below.

Constructor General Syntax
Default public className()
    // Initialize instance variables here
Initialization public className(parameterList)
    // Initialize instance variables here
Copy public className(className formalIdentifier)
    // Initialize instance variables here

All constructors have the same name as the class itself (represented by className). They differ only in their parameter(s). In fact, the compiler keeps track of which constructor is being invoked by matching the parameters in the invocation (by type and number) with the appropriate constructor. The default constructor has no parameters.

An initialization constructor has one or more parameters (represented by parameterList). If two initialization constructors have the same number of parameters, there must be some difference in the sequence of parameter types. For example, you could not have two initialization constructors both of which had two parameters; an int and a float in that order. The compiler would have no way of telling them apart. You could, however, have one constructor with an int and a float parameter and another constructor with a float and an int. Since the parameters are in a different order (by type), the compiler could keep them apart.

Class Methods

Class methods allow an object to communicate with its environment. You can think of a method invocation as a request. Some methods ask an object to change its state by altering the value of  one of its instance variables. These methods are known collectively as setters because each one begins with the word "set" followed by the property whose value is to be altered. There is often a setter for each instance variable.

Other methods ask an object to report on its current state. These methods are known as getters because each begins with the word "get" followed by the desired property. There is often a getter for each instance variable.

Often, there are other class methods that represent more complicated requests. For example, in our Rectangle class, we will implement a method that returns the area of the rectangle and another that returns the perimeter.

In a way, methods give an object self-awareness. That is, an object responds appropriately to requests made by other objects within its environment.