Java: About Static Method/Class Method.

Static Method:

I have discussed  Static Variable before,  you can check it from here.

Now I am going to discuss about Static MethodIt is also called Class Method.

In general we can say that methods declared with the keyword Static as modifier are called Static Methods or Class Methods.

Static Method in Java is that type of method which belongs to a class rather than an object of a class. Static Methods are invoked without reference to a particular instance (object) of a class.

So, anyone can invoke a Static Method without having to instantiate an object.

Important Notes / Features:

1. In Static Method, you can only manipulate variables that are declared as static, not other variables. It is because, something that is common to a class cannot refer to things that are  specific to an object.

 2. Static Method can call only other Static Methods.

3. Static Method cannot reference to the current object using super or this keyword.

 *** static means that it cannot be changed

Code:

public class StaticMethod

{

static int value=10;

StaticMethod()

{

test2 test =new test2();

}

              public static int getValue()

                        {

                        return value;

                        }

                        public int againgetValue()

                        {

                        return value;

                        }

public class test2

{

test2()

{

int getvalue= StaticMethod.getValue();

System.out.println(“Test2  calling the value StaticMethod.getValue(): “+getvalue); //Correct

//int setvalue= StaticMethod.againgetValue();  ****

//System.out.println(“test2  calling the value  StaticMethod.againgetValue() “+setvalue); **

}

}

public static void main(String args[])

{

StaticMethod test=new StaticMethod();

}

}

 

*** These 2 lines  will give error message as Instant Method cant be call in this way.

OUTPUT:

Test2  calling the value StaticMethod.getValue(): 10

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: