Why do we create instances of classes?
On the net all are saying how to create an instance of a class but
WHY DO WE NEED TO CREATE AN INSTANCE OF CLASS???
Why do we create instances of classes?
On the net all are saying how to create an instance of a class but
WHY DO WE NEED TO CREATE AN INSTANCE OF CLASS???
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Nitin SontakkeRank #264 · 9.6K reputationPosted Oct 21, 2022, 12:19 AM EDT
First let me congratuate you for raising the 'why' question. While entire world might be thinking / believing something is obvious, but you should still be questioning that belief. That is how you learn.
Coming back to your question, please try to follow the anology of a drawing of a building and an actual building.
As you know, you cannot actually live in the plan of a building you need to build the building. Similarly, the class by itself is quite useless unless you create an instance.
As much physical space a plan of a building occupies, the same applies to class in memory (relatively nothing). And similar goes with physical building and a class instance (relative more).
Other similarity is, from a plan you can build several identical buildings in a housing society. In every building different people live. Similarly, from a Customer class several customer instances can be created and each instance belongs to a different customer.
With a bit of imagination, hopefully you will understand the point.
If you still have a question, please feel free to ask. Hope it clarifies.
Rajanikant HawaldarRank #110 · 20.2K reputationPosted Oct 21, 2022, 12:14 AM EDT
Lets say you are building some Marketing(or Sales) application. Then, there will be a class called Customer. You will create an instance of Customer class for each Customer you need to save. You cant save all Customers in single instance. Each Customer will have different attributes. Like First Name, Last Name , email, phone number, address, customer type etc.
In the above code example, you are trying to create an instance of Customer. If you have lot of Customers, then you definitely create an instance for each Customer to keep track of all Customers.
Sam HobbsRank #107 · 20.5K reputationPosted Oct 21, 2022, 12:06 AM EDT
Suppose you have a blueprint of a home or building. A blueprint is a design of something. Can anyone live or do business in a blueprint?
Sam HobbsRank #107 · 20.5K reputationPosted Oct 23, 2022, 2:03 AM EDT
A blueprint is a drawing of a building. I am sorry I did not say that in my answer; I assumed you knew that.
The accepted answer says what I said except with more words.