The difference between regular (non-static) and static methods
Java is a Object Oriented Programming(OOP) language, which means we need objects to access methods and variables inside of a class. However this is not always true. While discussing static keyword in java, we learned that static members are class level and can be accessed directly without any instance. In this article we will see the difference between static and non-static methods.
Static Method Example
class StaticDemo
{
public static void copyArg(String str1, String str2)
{
//copies argument 2 to arg1
str2 = str1;
System.out.println("First String arg is: "+str1);
System.out.println("Second String arg is: "+str2);
}
public static void main(String agrs[])
{
/* This statement can also be written like this:
* StaticDemo.copyArg("XYZ", "ABC");
*/
copyArg("XYZ", "ABC");
}
}
Output:
First String arg is: XYZ
Second String arg is: XYZ
As you can see in the above example that for calling static method, I didn’t use any object. It can be accessed directly or by using class name as mentioned in the comments.
Non-static method example
class JavaExample
{
public void display()
{
System.out.println("non-static method");
}
public static void main(String agrs[])
{
JavaExample obj=new JavaExample();
/* If you try to access it directly like this:
* display() then you will get compilation error
*/
obj.display();
}
}
The difference between regular (non-static) and static methods
Reviewed by Anonymous
on
June 12, 2018
Rating:
No comments: