View RSS Feed

My Java Tips

Static/Non static methods - Example

Rate this Entry
by , 06-02-2011 at 08:12 PM (3095 Views)
I will present an example to show the difference between static and non-static methods.

Go through the example below:

Java Code:
public abstract class AbstractExample {

   public static void foo() {
      System.out.println("Static foo called.");
   }

   public void bar() {
      System.out.println("Non-static bar called.");
   }
}

public class AbstractCaller extends AbstractExample {

   public static void main(String[] args) {
      
      AbstractExample.foo(); \\ this is where we get our AnimalCount for exmple
      AbstractCaller ac = new AbstractCaller();
      \\ac.foo(); - NO NEED TO HAVE ac IF WE WANT TO CALL foo();
      ac.bar();
   }
}
Hope things are clear now.

Submit "Static/Non static methods - Example" to Facebook Submit "Static/Non static methods - Example" to Digg Submit "Static/Non static methods - Example" to del.icio.us Submit "Static/Non static methods - Example" to StumbleUpon Submit "Static/Non static methods - Example" to Google

Categories
Java SE

Comments