Like static variable it is also the scope of class. We know that to call a method object is needed but if the method is declared as static then no need to create object for calling the method because it can be called with the class name or we can call a static method from a static or non-static method without its class name. If we try to call a instance method from a static method directly by its method name then the compiler will give compilation error saying " non-static method method_name( ) cannot be referenced from a static content " .

Why compiler gives such type of error ?
For accessing a instance method we need to create an object and must be a part of JVM to restrict calling here but compiler is restricting while compiling  because the compiler is not sure that whether you have created an object in your program or not to access the instance method. That is why it is restricting while compiling our source file. For ex-

public class prog3 {

void display( ) {

System.out.println("Instance method");

}

public static void main(String sush[ ]) {

display( );  //Calling instance method "display()" from static 
               method main()

    }

}


In the above example display() is a instance method and we are trying to call it from a static method i.e main() , hence compiler is giving error because compiler is not sure for an object creation by code developer.

Note : We can reference an static method from a static or non-static method directly because it doesn't need any object for calling. 

Important points regarding static method 

1 > Like all others static method it can have an argument,return type, modifiers.

2> Any static method cannot be override.

3> We cannot declare two static method within  a class with same name.

4> Like all other methods we can overload static method as well.

5> Cannot declare any static variable in a static or non-static method Click here for details .

2 comments:

Blog Archive

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic