Chapter 9 - Programming Paradigms
Chapter 9 - Programming Paradigms
As we have previously stated that Object Oriented paradigm (often written O-O) focusses on the
objects that a program is representing, and on allowing them to exhibit "behavior". This focus on
creating programming constructs called Objects which binds data with their operating procedures.
class Employee
{
protected int empNo;
protected string empName; // Instance variables
Note, that in the above output, since emp1 object is created using the default constructor the
empNo and empName attributes are not initialized.
The child class inherits the attributes of its parent class, and you can use those attributes as if they
were defined in the child class. A child class can also override data members and methods from the
parent. We will be 2 sub classes derived from the “Employee” class. Following class hierarchy
diagram illustrates this.
· In the constructor here, inherited attributes are accessed using the base keyword.
· this keyword is used to access the attributes of the same class.
· getNetSalary() method is overridden in this class to implement the exact salary calculation
process for a Salaried Employee.
· If override keyword is replaced with new keyword the getNetSalary() method here will be
added as a new method without overriding the parent class method. However, to implement
the polymorphism (see below) the method should be successfully overridden.
Similarly, let us now see the code “HourlyPayEmployee” class. Add a new class in the same way as
you added the SalariedEmployee class.
· The constructor here makes a call to the appropriate constructor in the base class.
· this keyword is used to access the attributes of the same class, but it is not compulsory.
· getNetSalary() method is overridden in this class to implement the exact salary calculation
process for a Hourly Pay Employee which is different to how it is calculated for a Salaried
Employee.
Now modify the Main() as given below
class Program
{
static void Main(string[] args)
{
Console.WriteLine(">> Total Employees = " + Employee.getEmpCount());
Console.ReadLine();
}
}
· There are 3 Employee class object references emp1, emp2 and emp3.
· Employee class object reference can not only point to an object of the same classes but also
any object of sub classes derived from that.
Did you notice the salary of David is 0 (This is calculated using base class getNetSalary() method).
Salary of Anne is 23000 (This is calculated using getNetSalary() method of SalariedEmployee class)
Actually, when displayEmployee() method is called for each of the following object references, the
following happens.
emp1.displayEmployee() – this.getNetSalary() called the base class method as emp1 now points to
Employee object.