In Java, what’s the difference between an object and a class?

 

This kind of question is a test of your knowledge of the terminology associated with object oriented programming. Note that this question could just as well be asked in the context of a C++ programmer interview, or any programming position that requires object oriented programming for that matter.

The terms ‘class’ and ‘object’ are absolutely related to one another, but each term holds its own distinct meaning. The term ‘class’ refers to the actual written piece of code in which the class is defined. The properties of a class do not change before, during, or after the execution of a program.


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’. Animals have legs, bodies, and brains. This general concept of an Animal does not change.

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 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. As shown by this example, every object has a lifespan associated with it – a cat or zebra can not live forever. And, the properties of those objects can change as well while they ‘live’; if we have a ‘size’ variable defined in the class that would of course change as the cat object grows bigger.

So we can say that whereas a class is a general concept (like an Animal), an object is a very specific embodiment of that class, with a limited lifespan (like a lion, cat, or a zebra).