Java Tutorial: Defining a Function

Xah Lee, 2005-01

Here we show how to define your own function in Java.

In Java, everything is defined in a class, and class has methods. So, to define a unit that does your own computation, means defining a class, and a method inside the class. Here we show how this is done.

Save the following code into a file and name it “t1.java”.

class t2 {
    public int addone (int n) {
        return n+1;
    }
}

class t1 {
     public static void main(String[] arg) {
         t2 x1 = new t2(); 
         int m =x1.addone(4);
         System.out.println(m);
     }
}

Note the line “t2 x1 = new t2();”. It tells java that x1 is of type t2, and “new t2()” creates the object. Then, the “addone” function (called “method”) inside t2 can be used like this: “x1.addone(4)”.

It is all quite confusing but here's some outline of what's going on:

  1. Java code comes in unit of classes. (for example, not as blocks of function definitions and blocks of expressions)
  2. Each file can define many classes. The file's name must be identical to one of the class's name defined in the file. So, in our case, our file is “t1.java” and the corresponding class is “t1”.
  3. The main class of a file must have a method called “main”. This is the location the program starts to execute. In our example, class t1 has the method “main”.
  4. The other classes in a file are meant to serve as supporting role. (normally called auxiliary functions/subroutines)
  5. So, what we did above is that, we have main class t1, with t2 being a supporting class. And, we defined the addone method in t2. We call this method by first creating a instance of it, the x1. Then, call the methods of x1 to do our computation.

All Java programs follow the above outline.


Page created: 2005-01.
© 2005 by Xah Lee.
Xah Signet