InvokeDemo.java

Download InvokeDemo.java

 1: // Demonstration of various ways to invoke a method in Java.
 2: // Written 2002 by Wayne Pollock, Tampa Florida USA.
 3: 
 4: class InvokeDemo
 5: {
 6:     public static void main ( String [] args )
 7:     {
 8:         InvokeDemo obj = new InvokeDemo();
 9: 
10:         int i;
11:         i = obj.add( 2, 3 );
12: //      i = InvokeDemo.add( 2, 3 );  // Only if "add" declared "static".
13: //      i = add( 2, 3 );  // Only if "add" is "static" in current class.
14: 
15:         obj.aMethod();
16:     }
17: 
18:     /* static */ int add ( int num1, int num2 )
19:     {
20:         return num1 + num2;
21:     }
22: 
23:     void aMethod ()    // A non-static method.  Such methods have a
24:                        // "current" object.
25:     {
26:         InvokeDemo obj = new InvokeDemo();
27: 
28:         int answer;
29:         answer = obj.add( 2, 3 );
30: //      answer = InvokeDemo.add( 2, 3 );  // Only if "add" is "static".
31:         answer = add( 2, 3 );  // Only if add is method of curent class.
32: 
33:         System.out.println( answer );
34:     }
35: }