CIS 35A: Introduction to Java Programming

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

Classes

Objects and Classes
Create an object
Call methods

How to call the methods of an object

  • To call a method that doesn't accept arguments, type an empty set of parentheses after the method name.
  • To call a method that accepts arguments, enter the arguments between the parentheses that follow the method name, separated by commas.
  • The data type of each argument must match the data type that's specified by the method's parameters.
  • If a method returns a value, you can code an assignment statement to assign the return value to a variable. The data type of the variable must match the data type of the return value.

How to call a method

objectName.methodName(argumentList)

Example 1: Sends and returns no arguments

product.printToConsole();

Example 2: Sends one argument and returns no arguments

product.setCode(productCode);

Example 3: Sends no arguments and returns a double value

double price = product.getPrice();

Example 4: Sends an argument and returns a String object

String formattedPrice = product.getFormattedPrice(includeDollarSign);

Example 5: A method call within an expression

String message = "Code: " + product.getCode() + "\n\n"
    + "Press Enter to continue or enter 'x' to exit:";
Previous | Create | Call methods | Primitive and reference types | ProductDB class | ProductApp class | Next