CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Classes

Objects and Classes
Object
Methods

A method is a collection of statements that are grouped together to perform an operation.

How to code methods

  • To allow other classes to access a method, use the public keyword. To prevent other classes from accessing a method, use the private keyword.
  • To code a method that doesn't return data, use the void keyword for the return type.
  • To code a method that returns data, code a return type in the method declaration and code a return statement in the body of the method.
  • When you name a method, you should start each name with a verb.
  • It's a common coding practice to use the verb set for methods that set the values of instance variables and to use the verb get for methods that return the values of instance variables.

The syntax for coding a method

public|private returnType methodName([parameterList])
{
   // the statements of the method
}

A method may return a value. The returnType is the data type of the value the method returns. If the method does not return a value, the returnType is the keyword void. For example, the returnType in the main method is void.

A return statement is required for a nonvoid method.

A method that doesn't accept parameters or return data

public void printToConsole()
{
    System.out.println(code + "|" + description +  "|" + price);
}

A get method that returns a string

public String getCode()
{
   return code;
}

A get method that returns a double value

public double getPrice()
{
   return price;
}

A custom get method

public String getFormattedPrice()
{
    NumberFormat currency = NumberFormat.getCurrencyInstance();
    return currency.format(price);
}

A set method

public void setCode(String code)
{
    this.code = code;
}

Another way to code a set method

public void setCode(String productCode)
{
    code = productCode;
}
Previous | Product class | Instance variables | Constructors | Methods | Overload methods | this | Next