Inheritance
Products
Lets model e-commerce site having different products like Electronics, Kids Wear, Grocery, etc.
Electronic Item
Following are few attributes & methods for an Electronic product.
Grocery Item
Similarly, attribute & methods for a Grocery item.
Common Attributes & Methods
All these products Electronics, Kids Wear, Grocery etc.. have few common attributes & methods.
Specific Attributes & Methods
Also, each product has specific attributes & methods of its own.
Electronic & Grocery Items
Electronic Item & Grocery Item will have all attributes & methods which are common to all products. Lets Separate the common attributes & methods as Product
Modelling Classes
Advantages of Modelling Classes as above
- Reusability
- Clear Separation
- More Organized
Inheritance
Inheritance is a mechanism by which a class inherits attributes and methods from another class.
With Inheritance, we can have
Product is Super/Base/Parent Class and ElectronicItem is Sub/Derived/Child Class.
Super Class
Code
Output
Sub Class
The subclass automatically inherits all the attributes & methods from its superclass.
Example 1
Code
Output
Example 2
Code
Output
Example 3
Code
Output
In the above example, calling
Super Class & Sub Class
Superclass cannot access the methods and attributes of the subclass.
Code
Output
Sub Class Method
Code
Output
Calling Super Class Method
We can call methods defined in superclass from the methods in the subclass.