Interview Questions, Answers and Tutorials

12 Inheritance

12 Inheritance

Inheritance is a mechanism that allows classes to inherit the attributes of an existing class. It is used in situations where the subclass (which inherit attributes) is a subset of the superclass, whose attributes are Inherited. For example, suppose there are three classes of employee, developer, and tester. In this case, both developers and testers are employees. Here, the employee class can define generic attributes of employees. Specific attributes of developers can be defined in the developer class, while specific attributes of testers can be defined in the tester class. Both developer and tester are subclasses while an employee is a superclass. A class can inherit other class attributes using the keyword ‘extends’.
 
 
12.1 | Employee.java
 
The following code shows the inherent attributes of another class.
 
Employee superclass
 
 
 
12.2 | Developer.java
 
Developer subclass
 
 
 
Similar to class Developer.java, a separate class Tester.java can be defined for defining tester attributes.
 
The class below ‘Company.java‘ shows how to use the above-defined classes for adding and viewing employee details.
 
 
12.3 | Company.java
 
Company main class
 
The below screen is the output of the above codes.
 
output of the Company main class