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?
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).
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).
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With