Xah Lee, 2005-01, 2011-12-22
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.
blog comments powered by Disqus