Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we do not need to create object for static method?

Tags:

java

I know why main method is static. If it is static there is no need to instantiate that class by JVM. Without object we can call it. But why object is not needed to call static method?

Can anyone explain please?

like image 554
Rose Avatar asked Apr 26 '13 05:04

Rose


People also ask

Why object is not needed for static method?

Since they belong to the class, so they can be called to without creating the object of the class. Important Points: Static method(s) are associated with the class in which they reside i.e. they are called without creating an instance of the class i.e ClassName. methodName(args).

Can we use static variable without creating object?

A static filed/variable belongs to the class and it will be loaded into the memory along with the class. You can invoke them without creating an object. (using the class name as reference).

Can object be created for static?

Since static variables belong to a class, we can access them directly using the class name. So, we don't need any object reference. We can only declare static variables at the class level. We can access static fields without object initialization.

Why do we create non-static objects in Java?

In a simple way, we have to create an object of the class to refer to a non-static variable from a static context. A new copy of all the non-static variables is created when a new instance of variable is created. So, we can access these variables by using the reference of the new instance of the class.


2 Answers

A static method is associated with the class, not with any instance of the class.

See http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

like image 115
digitaljoel Avatar answered Oct 13 '22 01:10

digitaljoel


Consider this example, there is a family containing a mother and three children. Mother brings three ice cream cones to each of the children, but brings only one PSP for all the three children. All children use the same PSP but they have their own ice creams.

Here ice cream is a not-static thing (method/variable), PSP is the static thing, Mother is the class, children are objects.

It's pretty simple. Static belongs to a class, it is common for all the objects of a class. Not-static things are object specific.

like image 34
venki Avatar answered Oct 13 '22 02:10

venki