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:
All Java programs follow the above outline.
Page created: 2005-01. © 2005 by Xah Lee.