I know that static functions are class wide, and only a single copy exists for a static function for all the objects instantiated. A static function can also be used without instantiating other objects of the class in which it is declared.
Now what about functions that are declared class wide? What is the difference? I know that seperate memory space is only allocated for the attributes of the class. Not the methods/functions. So what is the exact difference?
Functions are called methods in Java. There are no functions in Java.
Non-static methods work on a specific instance of the class that they are in. Inside the method, you can use the this keyword, which refers to the object that the method was called on. You can also directly access the non-static member variables of the object that the method was called on.
Sid Kar wrote:So I've established that the difference between static methods, and class-wide methods in Java are that:
Just to be sure there is no confusion: static methods are class methods. Static methods are for the whole class, they don't work on any particular instance of the class. Non-static methods do work on one particular instance of the class.
Sid Kar wrote:2. I can access member variables using the object.
I don't know what you mean with "using the object". In a non-static method, you can access the member variables of the object that the method was called on directly.
Sid Kar wrote:However in terms of internal memory representation, only one copy of both methods, and static methods exist. Is this not correct?
Yes, only one copy of the bytecode of the method exists in memory.
If a class has some method, you can access those methods only by creating an instance of a class. And if you want to call some method inside the class itself then you can access it using this keyword.
If a class has some static method, you don't need an instance of a class for accessing that method. You can call static method like this <ClassName>.<static methodName> and if you want to call this method inside the class itself, simply call by methodName only.
Joined: May 23, 2011
Thank you Abhishek. I was kind of thinking about the internal memory representation of methods in Java and trying to figure out in what way a static method differs from a non-static method. I have a better idea now. Thank you. I have marked the thread as resolved.