Method Creation

In this chapter you will learn:

  1. What is the general form of a method
  2. How to add a method to a class

General form of a method

This is the general form of a method:

type methodName(parameter-list) { 
    // body of method 
}

type specifies the returned type. If the method does not return a value, its return type must be void. The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters receive the arguments passed to the method. If the method has no parameters, the parameter list will be empty.

Adding a Method to the Class

Add a method to Box,as shown here:

class Box {//from   j a  va2  s  .  c  o  m
  int width;
  int height;
  int depth;
  void calculateVolume() {
    System.out.print("Volume is ");
    System.out.println(width * height * depth);
  }
}

public class Main {

  public static void main(String args[]) {
    Box mybox1 = new Box();
    mybox1.width = 10;
    mybox1.height = 20;
    mybox1.depth = 15;

    mybox1.calculateVolume();

  }
}

This program generates the following output:

Next chapter...

What you will learn in the next chapter:

  1. Syntax for return statement
  2. How to return a value from a method
  3. How to return an object from a method