...

/

Defining a Class’s Methods

Defining a Class’s Methods

In this lesson, we will define methods within a class definition.

We define a method in much the same way that we define a constructor. Like constructors, methods have headers, but their syntax is slightly different, as we will see.

The method greet

The public methods of a class define the behaviors that objects of the class have. Our class Greeter has the method greet, which displays an object’s greeting. Its definition within the class appears as follows in lines 5 through 9:

Press + to interact
public class Greeter
{
private String greeting;
/** Displays the greeting. */
public void greet()
{
    System.out.println(greeting);
} // End greet
. . .
} // End Greeter

The method displays the string that the data field greeting represents. Recall that data fields are available by name throughout the definition of the class. Thus, any method definition within the class can use greeting by name. Also, remember that each object of the class Greeter has its own instance variable greeting, so this method displays the object’s own greeting.

A method, such as greet, that performs an action but does not return a value, as a result, is known as a void method. This particular method has no formal parameters, although void methods can certainly have them.

The program given below contains the definition of the class Greeter as we have defined it so far.

Press + to interact
/** Greeter.java by F. M. Carrano
A class that represents a greeting.
Data: A string
Behaviors:
Construct a new greeting
Display the greeting
*/
public class Greeter
{
private String greeting;
/** Creates a default Greeter object. */
public Greeter()
{
greeting = "Hello, World!";
} // End default constructor
/** Creates a Greeter object from the string newGreeting. */
public Greeter(String newGreeting)
{
greeting = newGreeting;
} // End constructor
/** Displays the greeting. */
public void greet()
{
System.out.println(greeting);
} // End greet
} // End Greeter

The data field greeting is private, as is typically the case for the data fields of a class. As a result, other classes cannot access or change the value of greeting directly by using the variable greeting. Although we can look at a Greeter object’s greeting by calling the method greet to display it, as the figure given below illustrates, we have no way to get—that is, to retrieve or access—the greeting as a string. Furthermore, objects of the class Greeter cannot be changed, as they have no methods to do so. Recall from the ...

Access this course and 1400+ top-rated courses and projects.