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
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:
5. View the output in the console as shown below:
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:
Post a Comment