does an object get created on the heap if i call a static method of a class.
i.e. lets say i write string str=ClassTest.methodReturnString(); does this mean that an object of type ClassTest will eb created on the java heap?
Stanley Walker wrote:does an object get created on the heap if i call a static method of a class.
i.e. lets say i write string str=ClassTest.methodReturnString(); does this mean that an object of type ClassTest will eb created on the java heap?
No. That's why you don't need an instance of the class to execute a static method.
"does an object get created on the heap if i call a static method of a class."
If you call static method on class of object, it is just reference of class it wont allocate any memory.
If you call it on object, certainly while creating object of call it will allocate memory for it.
so i guess it means that if we have a contructor in that class that will not run, if we call a static method of that class. what about the static block in that class. while calling the static method it will most definitely run, rite?
so why dont we mark all methods as static... wouldnt it be a better performance wise scenario.. no objects get created on the heap and the constructor code can be put in the static block..
i guess we would not be able to have overloaded constructors..
Stanley Walker wrote:so why dont we mark all methods as static... wouldnt it be a better performance wise scenario.. no objects get created on the heap and the constructor code can be put in the static block..
That's not the constructors are for. They are for creating objects. Use of static methods are very limited in OOP, they are mainly used in Factory methods, Singletons, defining constants (now Enums are prefered though) etc.. And creating objects are not much of a performance issue as garbage collector take care of unused objects with highly optimized compilers, JVMs we have these days.
Post by:autobot
Would you like to try a free sample? Today we are featuring tiny ads:
a bit of art, as a gift, that will fit in a stocking