Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Experiment no :- 03

Title: To study Inheritance,Interfaces and implement the program.


Problem Statement: An employee works in a particular department of an
organization. Every employee has an employee number, name and draws a
particular salary. Every department has a name and a head of department. The
head of department is an employee. Every year a new head of department takes
over. Also, every year an employee is given an annual salary enhancement.
Identify and design the classes for the above description with suitable instance
variables and methods. The classes should be such that they implement
information hiding. You must give logic in support of your design. Also create
two objects of each class.
Theory:

An interface in Java is a blueprint of a class. It has static constants and abstract


methods. The interface in Java is a mechanism to achieve abstraction. There can be
only abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java. In other words, you can say that
interfaces can have abstract methods and variables. It cannot have a method body.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

Program:
class Employee
{
String empName; int empNumber; double salary;
public Employee(String empName,int empNumber,double salary)
{
this.empName = empName; this.empNumber = empNumber;
this.salary = salary;
}

public void incrementSalary(int incSalary)


{
salary += incSalary;
System.out.println("\nSalary of "+empName+" incremented to "+incSalary);
}
public void displayEmpInfo()
{
System.out.println("\nEmployee Name : "+empName+"\nEmployee Number :
"+empNumber+"\nSalary : "+salary);
}
}
class Department
{
String depName; Employee head;
public Department(String depName,Employee head)
{
this.depName = depName; this.head = head;
}
public void changeHOD(Employee newHead)
{
head = newHead;
System.out.println("\nHead of "+depName+" Department changed to
"+head.empName);
}
public void displayDepInfo()
{
System.out.println("\nDepartment Name : "+depName+"\nHead :
"+head.empName);
}
}
public class Exp_3
{
public static void main(String[] args)
{
Employee e1 = new Employee("SIDDHESH",430,100000);
Employee e2 = new Employee("GANESH",90,100000);
Employee e3 = new Employee("SIDZZ",20,100000);
Department d1 = new Department("COMPS",e1);
Department d2 = new Department("IT",e3);
d1.displayDepInfo(); // changing head of department d1
d1.changeHOD(e2);
d1.displayDepInfo();
e3.displayEmpInfo(); // incrementing salary of employee e3
e3.incrementSalary(500);
e3.displayEmpInfo();
}}
Conclusion: It is used to achieve abstraction. By interface, we can support the
functionality of multiple inheritance. It can be used to achieve loose coupling.

You might also like