Software & Finance

Java - Static Functions Explained With Example

static functions can be accessed wiithout creating an instance of a class or objects. We can access the function with class scope.


Remeber that in Java all non static functions are considered as virual, if they are public. You have to make it either private or use final keyword to remove the default virtual feature in each function in the Java classes.


You can access the method draw from the class Shape with the syntax Shape.draw(). You do not need to create a object to invoke the method draw().



Source Code




class Shape



    public Shape()





    static public void draw()


        System.out.println("Drawing Shape");





class StaticFunction


    public static void main(String[] args)


        Shape object = new Shape();


        System.out.println("\n\nNow Drawing Objects\n");


        // object.draw(); // It is not a good practice to use this syntax even if it works.

        Shape.draw(); // It is the correct usage of calling static function.






D:\Program Files\Java\jdk1.6.0_23\bin>javac


D:\Program Files\Java\jdk1.6.0_23\bin>java StaticFunction


Now Drawing Objects 

Drawing Shape