Google+

100. Inheritance







Inheritance is a mechanism in which one object acquires the properties of another object. The following example will show you how the objects are hierarchically organized and how the child objects inherit the properties from the parent objects


In programming like Java, the idea behind using Inheritance concept is to create a new classes built upon existing classes. i.e. The new classes reuses the methods and data by inheriting them from the existing classes.

A subclass inherits all of the instance variables and methods defined by the superclass and adds its own, unique elements.

A subclass uses extends keyword to inherit all the members of superclass as shown below:

class subclass-name extends superclass-name
{
    // Body of the class


Lets implement this on Eclipse IDE:

1.Create 'Car' superclass under any project as shown below and save:



2. Create 'BenZ' subclass which inherits the members of 'Car' superclass using 'extends' keyword as shown below and save:



3. Create another class 'InheritanceDemo' to access the instance variables and methods of subclass 'Benz'  (Which includes the instance variables and methods inherited from the superclass 'Car' along with the instance variables and methods declared in the subclass 'Benz') as shown below:



4. Save and Run the 'InheritanceDemo' class
5. View the output in the console as shown below:



Download this Project:

Click here to download the project containing 'Car' ,'Benz' and 'InheritanceDemo' class files used in this post (You can download this project and import into Eclipse IDE on your machine)




Please comment below to feedback or ask questions.

'subclass cannot access private members of superclass' will be explained with an example in next post.




No comments: