Inheritance like other OOPS features is also a real life concept. In real world children acquire or inherit the properties and behaviour of their parents. These properties can be biological like color of hair, color of eyes, facial similarities or monetary like land, money, house etc. Similarly the behavioural characteristics of a child are also similar to his or her parents. When a child inherits these properties from parents he doesn't need to earn them again. He can use the inherited property (house,money) of his parent as if he owns them. What the child earns on his own can be said to be as a kind of "bonus" for him.
In OOPS, the concept of inheritance is the same as it happens in real. A class can "inherit" properties and behaviours from another class, which be now be called as its parent. By inheriting the properties of an existing class, the other class is promoting "reusability" which has its own advantages.
To define "Inheritance is the process of declaring a class using the properties and behaviours of an existing class". The main benefit in inheritance is that the members of the existing class can be used by the child class without having to re declare them.
Definitions
1. Base Class : The class that is being inherited by other classes is called a "base" class. It can also be called as "parent" or "super" class. A base class can decide which properties or behaviour it wants the child to access and which ones to hide. This is done using the access specifiers like "private", "public" etc.
2. Sub Class : The class that is inheriting the properties is called a "sub" or "child" or "derived" class. A class can inherit the properties from a single or multiple parent classes. A child class can also act as a parent for yet another class.
Advantages of Inheritance
1. Saves memory : Any thing which is needed more than once can be declared in the base class. Any class which needs an already defined member can simply inherit the base class resulting in saving of memory.
2. Saves time : Reusing the same code saves time in terms of retyping the code and debugging. Debugging or removing the errors of the program is done only once since the same code is being used by all the child classes.
3. Uniformity : Since the child classes are not declaring its own members there is no possibility of declaring same variable with different type and size in different classes. For example a variable named "address" can be defined in the first class with a size of "20" while the same variable can be defined with a different size in the second class. Inheritance will make sure that all the classes are using the same variable leading to standardisation of the program.
0 comments:
Post a Comment