Manaf Abdul wrote:Generally the example given for classes and objects is like : If I have a class car then it can have various objects like bmw, mercedes etc. and other similar examples. But isnt this an example of inheritance? So whats the difference ?
It's matter of is-a or has a relationship. For example, a Car class will contain an engine, and wheel both of which are classes on there own (has-a relationship) but a car is not an engine or a wheel. Where did you see the example that you describe?
This is a class:
When you execute this:
...then myClass is an object in memory. None of this has to do with inheritance.
In your example, Car, BMW, Mercedes are all classes. You can create objects from them if they have a constructor that you can access (usually public).
Now Car itself might be a subclass of Vehicle. Other subclasses of Vehicle might be Bus, Tractor, Train, Plane, etc. Or should there only be a class Vehicle, with a field that says what kind of vehicle any particular instance is?
Then should you have subclasses of Car named Bmw, Ford, Audi, etc? In this case, probably having a field in Car is sufficient. But what do we do about Tesla ? Car has a gasTankCapacity field - but a Tesla does not have a gasTank. So should Tesla should be a Car with capacity=0, should it be a subclass of Car, or should it be a subclass of Vehicle? These are design choices that you must make.
Another example is Animal.
Human is a subclass of Animal. Should Man and Woman be subclasses of Human, or should there just be a field called sex?
In many cases, there is no actual correct answer - each of the choices have their advantages and disadvantages. It is up to the developer to make the choice. It often comes down to haw many common fields to the objects have.