Thursday, April 5, 2012

Parent Class and Child Class

Hello Everyone, In this post I will discuss about the Parent Class and Child Class.

From earlier posts we already know how to make a class, and use the class by creating objects. That is good but how would you feel when you have to make several class, that are almost similar to each other. That would be a pain to type same codes and statements again and again, isn't it??

Here comes the concept of Parent Class and Child Class or also known as Super Class and Sub Class.

In this concept, we make a Parent class, and the Child Class inherits the attributes or characteristics of the Parent Class.

How do we do that? Lets check with an example:

>>> class autoMobileParent:
               car1 = "This is Maruti 800"
               car2 = "This is Mercedez Benz"
               bike1 = "This is Bajaj Pulsar"
               bike2 = "This is Harley Davidson"

   
>>> autoMobileParent.car1
'This is Maruti 800'
>>> autoMobileParent.car2
'This is Mercedez Benz'
>>> autoMobileParent.bike1
'This is Bajaj Pulsar'
>>>

Okay we have created a Parent Class, now we will make Child Class and make Make Some Objects.

>>> class childCar(autoMobileParent):  <--Here we inherited the Parent Class
                  car3 = "This is a Van"

   
>>> car = childCar()
>>> car.car1
'This is Maruti 800'
>>> car.car2
'This is Mercedez Benz'
>>> car.car3
'This is a Van'
>>>

>>> class childBike(autoMobileParent):  <--<--Here we inherited the Parent Class
               bike3 = "This is Royal Enfield"

Lets make another, just for fun..
  
>>> bike = childBike()
>>> bike.bike1
'This is Bajaj Pulsar'
>>> bike.bike2
'This is Harley Davidson'
>>> bike.bike3
'This is Royal Enfield'
>>>

Notice here, that even if we did not create car1, car2 or bike1, bike2 for the respective child class, they inherited it from the Parent Class.

Okay so I hope Super Class and Sub Class should be clear with you now, practice it, and Don't forget to check my next post.

Thank You!

0 comments:

Post a Comment