Why I need object when a class have Identity, attribute & behavior? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why I need object when a class have Identity, attribute & behavior?

20th Apr 2018, 12:36 AM
ⓤⓝⓢⓜⓐⓡⓣ ⓑⓞⓨ
ⓤⓝⓢⓜⓐⓡⓣ ⓑⓞⓨ - avatar
5 Answers
+ 9
An object is an instantiation of a class. A class is like a blueprint of a building (it's not the building itself). You could build many buildings the same (or similar), using the blueprint. The buildings in this metaphor, would be the objects. The only exception, is that you can have static member functions in classes, which can be called without creating an object. A good example of this is a Maths class. If you wanted to create a game, with characters (players), an object might represent each player. You'd therefore need one object per player. And each player would have the same blueprint, but different values at run-time (different Health Score, different weapons etc). I hope that makes some sense?
20th Apr 2018, 12:48 AM
Emma
+ 4
Static is used when you don't need to create an object. Objects are effectively run-time versions of classes, that have their own data. Static is used when you don't need to store data, but you still need functionality of some kind. The Math class doesn't need to be instantiated into an object, as you don't need different instances of it. Pi is still pi, and the formulas (sqrt etc), are the same no matter what. So, you just need to run functions from the class, or to get constants from the class. Math.pi or Math.sqrt(16). I hope that is clearer now. If we take the building metaphor again, blueprint of a house is a class, houses created from that blue print are objects. The maths needed to help build the house, stays the same in functionality (stays the same = static). Therefore no object needed for the maths!
20th Apr 2018, 4:01 AM
Emma
+ 2
Xan Thank's a lot now I clearly understand it. I need to red more to know more. Can u please explain static? with your same example above or a better example of static. Thank u.
20th Apr 2018, 3:56 AM
ⓤⓝⓢⓜⓐⓡⓣ ⓑⓞⓨ
ⓤⓝⓢⓜⓐⓡⓣ ⓑⓞⓨ - avatar
+ 2
the class is a "schema", the object is the complete construction.
23rd Apr 2018, 8:03 AM
Bauglir
Bauglir - avatar
+ 1
static is sharing variable you can access it by classname.variable not need to create object . for example if you want to know how much objects created . class Csharp { static int num=0; Csharp() { num+=1;} } in this example when you create object then 1 added in num variable.
22nd Apr 2018, 7:46 AM
Dilshad Ahmad
Dilshad Ahmad  - avatar