learning java - sidramaqsood/learning GitHub Wiki
Q NO 3= difference between object and class?
ANS=
The terms ‘class’ and ‘object’ are definitely related to one another, but each term holds its own distinct meaning. Let’s start out by explaining what the term “class” means in the context of OOP. The term ‘class’ refers to the actual written piece of code which is used to define the behavior of any given class. So, a class is a static piece of code that consists of attributes which don’t change during the execution of a program – like the method definitions within a class.
An object is an instance of a class
The term ‘object’, however, refers to an actual instance of a class. Every object must belong to a class. Objects are created and eventually destroyed – so they only live in the program for a limited time. While objects are ‘living’ their properties may also be changed signficantly.
An example will help clarify what we’ve said. Suppose we have a class called ‘Animal’. All Animals have bodies and brains – and these could be the attributes of our fictional Animal class. We can also add some methods that would be common to all Animals – like “movement”, because all animals can move (maybe you can think of a better example for methods, but hopefully you get the point). So, the idea you really want to enforce in your own mind is that this very general ‘template’ of an Animal does not change – it’s simply just some lines of code that define the Animal class.
An instance of the Animal class would be a specific animal – like a lion, a cat, or a zebra. These instances of the Animal class would be called objects. Whereas the Animal class is a general concept, the instances of that class – the lions, cats, etc – take that general concept and create a real instance of it.
That is why programmers define constructors for their classes – so that when someone wants to create an object of the class, he/she can just pass in the actual properties that he/she wants the object to have – like what kind of animal it is, the name, the weight, etc. So, you can think of a constructor as something that brings the class to life – which is why it is called a constructor, because it constructs a specific instance of a class