Explanation
This Java code demonstrates a fundamental concept in Object-Oriented Programming (OOP) called inheritance. It defines two classes: employee and department.
-
employeeClass:- This class serves as the base class or superclass.
- It represents a generic employee with two private attributes:
eno(employee number, an integer) andename(employee name, a string). Beingprivate, these attributes can only be accessed directly from within theemployeeclass itself, enforcing encapsulation. - It provides two public methods:
setemp(int no, String name): This method is used to set the employee number and name.putemp(): This method is used to display the employee number and name to the console.
-
departmentClass:- This class is the derived class or subclass. The
extends employeekeyword signifies thatdepartmentinherits fromemployee. This means adepartmentobject automatically gains all the public and protected members (attributes and methods) of theemployeeclass. - In addition to the inherited members,
departmenthas its own specific private attributes:dno(department number, an integer) anddname(department name, a string). - It also provides its own public methods:
setdept(int no, String name): This method sets the department number and name.putdept(): This method displays the department number and name.
- The
mainmethod is located within thedepartmentclass, making it the entry point for execution.- Inside
main, an objectdof thedepartmentclass is created. d.setemp(22,"Nathan");: Here, thedepartmentobjectdcalls thesetemp()method. This method was inherited from theemployeeclass. It sets the employee number to 22 and the employee name to "Nathan" for this specificdepartmentobject.d.setdept(1,"Programming");: Thedepartmentobjectdthen calls its ownsetdept()method to set its department number to 1 and department name to "Programming".d.putemp();: Thedepartmentobjectdcalls the inheritedputemp()method to display the employee details (Nathan, Empno 22).d.putdept();: Finally, thedepartmentobjectdcalls its ownputdept()method to display the department details (Programming, Deptno 1).
- Inside
- This class is the derived class or subclass. The
In essence, the department object d now holds both employee-specific information (inherited) and department-specific information (its own), and can perform operations related to both, showcasing how inheritance allows a subclass to extend and specialize the functionality of a superclass.