Inheritance: More than just titles or money

0

Hi there readers,

We have talked about the first principle of object oriented programming in an earlier post. Now, it would be time to talk about the second one, inheritance. In the normal world, we talk about inheritance when one is about to receive some piece of land or a title from a loved one in his/her family. In the programming realm, it is more than this. In OOP, inheritance happens when a class is based on another class . This relation is special because they share the same implementation. Doing so, the class (B), who inherits from the other (A), share the same behavior that A has. But why would programmers act like this? Why not simply copy-paste the code from the class A to the class B? Those are actually good questions you might have had.

I don’t know if you remember from earlier posts, but I had mentioned that having a software which had a lot of code was not the goal you should think of while writing code. Sometimes, there won’t be any other way than having a software which has 10,000.0 lines of code and it is okay. But what we aimed for is having a software that is as maintainable as it can be. When I say maintainable, what I mean is that simply finishing a project won’t mean that it won’t change in one day or one month or five years. A query from a client can make your project change over time,and while you’re going through those changes, you don’t want to change all the code that was written before. Having maintainable code can be achieved through different methods, and by this I don’t mean the methods we usually write in order to complete operations. One of them is code reuse.

Like it was said earlier, class B inherits from class A. Inheritance is a mechanism for code reuse. Not only B gets all the same behavior that A has,  but B has accessed to all the attributes from the class A. Has much as inheritance is a good principle to follow while doing OOP, there is something that we must keep in mind while using inheritance. When a class inherits from another, what we’re trying to achieve is to specialize a concept by adding new behaviors to the class. Basically, we have what we call the superclass which has some states and behaviors that can be common for many situations. Then, we have the subclasses which inherits those traits but add new ones. For example, we could have the superclass Person which has a Weight, Name and Age. Now, we have the classes Student, Manager and Employee.

The Student objects, since inheriting from Person, already have Name,Weight and Age. But a student has more than simply that like a grade point average (GPA) or a student id (ID). Employee is also inheriting from Person but has the properties Salary and  Bonus. Finally, we have Manager which inherits from Employee but only overrides behaviors from Employee.

That’s a benefit from inheritance. Even though we inherits from a superclass, if we like the behaviors from the previous class but there is some things that need to be change, then we can override those behaviors in order to achieve what we truly wish to do. Down below, we’ll see in code exactly what I said we can do with inheritance.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
      static void Main(string[] args)
      {
         Person aPerson = new Person("Bob", 70.45, 23);// creating a person
         aPerson.SayingHello("Sarah");

         Student aStudent = new Student("Bobby", 1023453235, 3.98, 83.67, 22); //creating a student
         aStudent.PrintStudentAverage(); //Printing the student's average

        Employee anEmployee = new Employee("Tom", 5, 25.50, 23); //creating an employee
        anEmployee.SayingHello(aStudent.Name); //The employee says hi to the student
        anEmployee.PrintEmployeeSalary(); // Printing the salary of the employee

        Manager aManager = new Manager("Kevin", 43.45, 23, 4);
        aManager.SayingHello(anEmployee.Name);
        aManager.PrintEmployeeSalary();

        Console.ReadLine();//Press Enter to quit this application
     }
   }

   public class Person
   {
     private double _weight; //we define the fields by starting with the underscore (_)

     public double Weight
     {
        get { return _weight; }
       set { _weight = value; } //We'll let the weight like this because over time, it can change
     }

     private String _name;

     public String Name
     {
        get { return _name; }
        set { _name = value; }
        //Usually, the name of a person does not change, so we'll make it private.
       //This means that no one who can access an object of Person will be able to modify the name
     }

     private int _age;

     public int Age
     {
       get { return _age; }
       set { _age = value; }
     }
     //Constructor
     public Person(String aName,double aWeight, int anAge)
     {
       Name = aName;
       Weight = aWeight;
       Age = anAge;
     }

     public Person() { }

     public void SayingHello(String personName)
     {
        Console.WriteLine("Hi, my name his : {0}. It his a pleasure to make your acquantaince {1} !", Name, personName);
     }
  }

     public class Student : Person
     {
        private int _studentID;

       public int StudentID
       {
          get { return _studentID; }
          set { _studentID = value; }
       }

       private double _gpa;

       public double GPA
       {
          get { return _gpa; }
          set { _gpa = value; }
       }

       private int _numberOfClasses;

       public int NumberClassesForTheSemester
       {
          get { return _numberOfClasses; }
          set { _numberOfClasses = value; }
       }

       private int _numberOfCredits;

       public int NumberOfCredits
       {
         get { return _numberOfCredits; }
         set { _numberOfCredits = value; }
       }

        public Student(String name, int id, double gpa,double weight, int anAge)
        {
           this.Name = name;
           this.StudentID = id;
           this.GPA = gpa;
           this.Weight = weight;
           this.Age = anAge;
        }

        public void PrintStudentAverage()
        {
            Console.WriteLine("The average of {0} is {1}", this.Name, GPA);
        }

        private void ComputeStudentGPA()
        {
           //not how we actually do it, it is more as a behaviour to add to this class
           GPA = NumberClassesForTheSemester / NumberOfCredits;
        }
     }

    public class Employee : Person
    {
      private double _hourlyWage;

      public double Salary
      {
         get { return _hourlyWage; }
         set { _hourlyWage = value; }
      }

       private int _bonus;

       public int EndOfyearBonus
       {
          get { return _bonus; }
          set { _bonus = value; }
       }

       private int _yearInCompany;

       public int YearsInCompany
       {
          get { return _yearInCompany; }
          set { _yearInCompany = value; }
       }

       public Employee(String name, int yearsOfLoyalty,double salary, int age)
       {
          this.Name = name;
          this.YearsInCompany = yearsOfLoyalty;
          this.Salary = salary;
          this.Age = age;
       }

        public Employee() { }

        public virtual void ReceiveBonus(int bonus)
        {
            EndOfyearBonus = YearsInCompany * 2 * bonus;
        }

        public void PrintEmployeeSalary()
        {
           Console.WriteLine("This is the salary : {0} $/h of {1}", this.Salary, this.Name);
        }
     }
     public class Manager : Employee
     {
        public Manager(String name, double salary, int age, int numberOfYears)
        {
           this.Name = name;
           this.Salary = salary;
           this.Age = age;
           this.YearsInCompany = numberOfYears;
        }

        public override void ReceiveBonus(int bonus)
        {
           EndOfyearBonus = 3 * YearsInCompany * bonus;
        }
     }
  }

Kevin

Advertisements

OOP: Do you object to this statement ?

0

Hi readers,

First of all, I’d like to wish you to have a wonderful holidays with your family, wherever you are at this moment. During the first lectures, we went over some of the basics of programming. Even though it might have seen like a lot, it was just the core fundamentals we needed to understand the basic logic in any given program. Don’t worry, we’ll cover some more later in the blog. Right now, with what we’ve seen so far, I thought it would be a good idea to get into the hype of object oriented programming.

Say what? Object oriented programming (OOP) ? Sounds funny huh? It is actually a really popular programming paradigm in the developer’s world. It is my belief that we ought all to know more about this. I don’t mean that we need to be expert in this particular field, but there’s so much to do with this paradigm that it would be a shame to not exploit what it gives us !

To begin, what is oriented object programming ? Wikipedia defines object oriented programming as the following: “a programming paradigm based on the concept of “objects”, which are data structures that contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.”  I’m going to roughly summarize this as a programming paradigm which able a given programmer to place any form of data in an “object” which can be use at anytime for any given purposes such as interact with it.

That’s some heavy abstract notions that was written. In this blog, I’m going to cover as much on this paradigm as I possibly can. OOP has a lot of advantages such as making code more flexible and more maintainable. As much as I would like to tell you that oriented-object programming is the best way to do things that you’d like to do, it is not always the case. In fact, like anything else this world, OOP has some downsides that can be unappealing like the effort it takes. To be really good in this paradigm, it takes a lot a thinking and creativity to create efficient objects which will help you reach your goals. Don’t get me wrong, I like OOP. Even if it takes some time and creativity, you must keep in mind that in any given programming paradigm, coding is a craft that takes time, no matter what you do.

Let’s head back to what OOP actually is. We saw some core basics that we all ought to master if we want to be good, or should I say, great programmers, such as loops or conditional structures (ex: if-else).  With these, we can now move to the next level, in this matter, OOP. In OOP, we define virtual objects in our software. Most of the time, we try to represent real objects from the world such as a car or a an animal (ex: a dog). More than just saying this an animal, we give this object specific behaviors with the help of methods.  Finally, at any time, an object can have a state too, such as being awake or tired in the case of a dog. To wrap up, in order to create an object Dog, we would have to define what is called a class named Dog which would be define with different attributes like a weight (double), a name (string) and a number of legs (int). To interact with this dog, we would have to define the different behaviors we expect to find in this object such as: walking, barking or sleeping. You’ll be able to see below an image that I found on the web,  which sums up what I’ve said

OOP_Objects

In the previous paragraph, I have mentioned a specific keyword of oriented object programming : class. A class is a template in which we will store all the data we need in order to define the object we want to create. That’s all there is to it. When we use objects from this class, we call them instances of the class. When I say instances I mean that once you have created an object of a particular class, you actually are creating a reference which is pointing to the data of this specific class. In short, in your code, you can have multiple references to the same class (instances) but, that does not mean they will contain the same exact data. Let’s say that you’re creating a zoo application. In a zoo, there is more than one animal of the same kind, but they aren’t identical. In the same with objects. Some can be identical. for given purposes, but some are simply not.

While we’re diving in the oriented object programming paradigm, we’ll get to see what truly makes a programming language like C# OOP with the help of encapsulation, inheritance and polymorphism. Without those three core fundamentals, you cannot use OOP with a language. But more on this in a later post.

Kevin