-1

If I create a custom class inside source file, and define a function inside that class, then instantiate objects using that class in main() function. Will the every object I create have that function created/stored inside it? If I create 100 objects, wouldn't it mean that I am actually storing/creating that function 100 times inside the object?

I learnt that if I make a function static, the function will be attached to the class instead of every object I create, and the objects we create using that class will not have the function created inside them.

I would like to have clear view of things and explanation of this matter. You should know by now that I am a beginner. So, I'll be grateful if someone can explain me about classes, objects, static key word and their behavior which I said before. Thank you.

Naveen Kumar
  • 64
  • 1
  • 7
  • 1
    I don't think that Java saves methods inside objects. The only thing that is saved inside the object and is unique to each object is their instance variables. It wouldn't make sense to save methods declared in class for each object - since they can't be changed. – Barracuda Sep 28 '21 at 05:01
  • So...there's no use of 'static' keyword then? I need to create object to call a function from inside main function if I don't use 'static' keyword. Doesn't it mean that if don't use 'static' keyword then every object will have it's own copy of that method? I may be wrong... Please explain this behavior to me? – Naveen Kumar Sep 28 '21 at 05:22
  • I don't know how java represents methods internally, but it just wouldn't make sense to save a method inside every object. I recommend you picking some book for beginners: Head First Java is good one, even though it's outdated. – Barracuda Sep 28 '21 at 05:26

1 Answers1

0

Consider, What's the difference between a method and a function?

In Java, the static keyword gives you something like a function: it has no access to any instance data. A method of course has access to the state of the object it was called on. This access is provided simply by passing one additional, implicit argument.

So there is no reason that both of these definitions cannot live exclusively within the class. Methods needn't be copied for each object, as the signatures do not change.

The reason you cannot call a non-static from a static, i.e. you cannot call a dynamic method from a static function, is that a static function does not have enough arguments to call a method. Specifically, it is missing the object reference which a method signature implicitly requires.

In the snippet myObject.method("foo"); two arguments are passed: the first argument is myObject and this argument is passed implicitly by the language. The second argument is "foo" and this argument is passed explicitly by the caller.

In the snippet MyClass.function("foo"); only one argument is passed, explicitly by the caller. MyClass is just a namespace for the function.

jaco0646
  • 13,332
  • 7
  • 54
  • 75