Abstract Class VS Interface

Abstract Class VS Interface

In this blog post I will discuss abstract classes and interfaces with comparing their differences and similarities. The concept of abstract classes and interfaces is a bit confusing for beginners of object oriented programming. Therefore, I am trying to discuss the aspects of both the concepts and compare their usage with a small demo for their usage with C#.

Let’s start with their appearance excluding the implementation. Both the abstract class and the interface just look like each other; however there are a lot of differences and similarities between them. Let’s explain both concepts and compare them.

What is an Abstract class?

An abstract class is a special kind of class that cannot be instantiated. So why do we need a class that cannot be instantiated?

We need a class that couldn’t be instantiated to be as a kind of contract that forces all subclasses to carry on the same hierarchies or standards. So its only a subclassed class that is inherited from.

What is an interface?

An interface is an entity that is defined by the word Interface, but it is not a class. It contains no implementations; only signatures of the methods. It has a common trait with the abstract class, which is that they are both used to define hierarchies for all subclasses or it defines specific set of methods and their arguments.

When to use each?

You use the interface when you want to support multiple inheritance, and you use abstract classes when you want to inherit from only one class.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.

The following table shows the differences and similarities between the abstract class and the interface:

Screenshot (39)

Making it easier to understand the difference, let’s see how it works with the code:

Abstract Class Student

Using System;
namespace AbstractVsInterfaces{

    Public abstract class Student{

     // these are the fields that we
     //could have in an abstract class
     Protected string id;
     Protected string name;
     Protected string major;

     //properties
     Public abstract String ID{
      get;
      set;
     }

    public abstract string name{
     get;
     set;
    }

    public abstract string major{
     get;
     set;
    }

    //complete methods with no abstract
    // keyword in the signature
    public string add(){
     return name + “with ID” + id
      + “is added successfully”;
    }

    public string delete(){
     return name + “with ID” + id
      + “is deleted !”;
    }

    // each major has a different calculation
    //to its major so I leave the method in an
    //abstract for and implement it differently
    public abstract string gpa();
   }
}

Interface Student

Using system;
namespace AbstractVsInterfaces{

    Public interface IStudent{

    //no fields
    String ID{
     get;
     set;
    }

    String name{
     get;
     set
    }

    String major{
     get;
     set;
    }

    //no implementations
    //everything is public
    String add();
    String delete();
    String gpa();
   }
}

Inherited Objects

BusinessStudent

Using system;
namespace AbstractVsInterfaces{
    //using the abstract class

    Public class BusinessStudent : Student{

    //since its using the abstract class then there
    //is not fields nor properties
    Public BusinessStudent(){
    }

    Public override string id{
     Get{
      return id;
     }
     Set{
     id = value;
     }
    }

    Public override string name{
     Get{
      return name;
     }
     Set{
      name = value;
     }
    }

    //methods that are already implemented
    //in the abstract class
    Public new string add(){
     return base.add();
    }

    Public new string delete(){
     return base.delete();
    }

    //this is the method that would
    //have different implementations
    //from major to another
    Public override string gpa(){
     Return base.name + base.id
      + “will be calculated later - abstract”;
    }
 }
}

EngineeringStudent

Using system;
namespace AbstractVsInterfaces{
    //using the interface
    Public class EngineeringStudent : IStudent{
    //fields are defined here not in the interface
    Protected string id;
    Protected string name;
    Protected string major;

    Public EngineeringStudent(){
     //constructor code
    }

    Public string id{
     get{
     return id;
     }

     set{
      id = value;
     }

    }

    Public string name{
     get{
      return name;
     }

     set{
      name = value;</p>
     }

    }

    Public string major{
     get{
      return major;
     }

     set{
      major = value;
    }

   }

    //all code implementation of add and delete
    // are written here not in the interface
    Public string add(){
     return name + id
      + “is added to the Engineering major”;
    }

    Public string delete(){
     return name + id
      + “is deleted from the Engineering major”;
    }

    Public string gpa(){
     return name + id
      + “will be calculated later- interface”;
    }
   }
  }
}

This was the difference between an abstract class and inheritance 😀
For any feedback or questions, you’re more than welcome to send me an email at yasmine.abdelhady@hotmail.com or reach me @yasabdelhady on twitter.

Advertisements

OOP Design Principles

OOP Design Principles

An application that implements Object-Oriented Programming concepts is distinguished by four design principles. At times, I used to think that understanding Object Oriented Programming concepts have made it difficult since they have grouped under four main concepts, while each concept is closely related with one another. Hence one has to be extremely careful to correctly understand each concept separately, while understanding the way each related with other concepts. These four principles are encapsulation, abstraction, inheritance, and polymorphism.

Easily remembered as A-PIE

Image

Abstraction

Polymorphism

Inheritance

Encapsulation

Abstractionmanual

Abstraction refers to the act of representing essential features without including the background details or explanations. It is the ability to generalize an object as a data type that has a specific set of characteristics and is able to perform a set of actions. Object-oriented languages provide abstraction via classes. Classes define the properties and methods of an object type.

For example, consider a television as an object. It has a manual explaining how to use the television. However, this manual does not show all the technical details of the television, thus giving only an abstraction to the user.

Polymorphism

Polymorphisms is a generic term that means ‘many shapes’. In other words, it means the ability to request that the same operations be performed by a wide range of different types of things. For instance, if both Customer and Vendor objects have a name property, and we can write a routine that calls the Name property regardless of whether we’re using a Customer or Vendor object, then we have polymorphism.

A vehicle is a good example of polymorphism. A vehicle interface would only have those properties and methods that all vehicles have, a few of which might include paint color, number of doors, accelerator, and ignition. These properties and methods would apply to all types of vehicles including cars, trucks, and semi-trucks.

Polymorphism will not implement code behind the vehicle’s properties and methods. Instead, polymorphism is the implementation of an interface. If the car, truck, and semitruck all implement the same vehicle interface, then the client code for all three classes can be exactly the same.

In OOP the polymorphisms is achieved by using many different techniques named method overloading, operator overloading and method overriding.

Inheritance

g2Inheritance is the idea of a class, called a subclass, based on another class, called a base class. Classes are created in hierarchies, and inheritance allows the structure and methods in one class to be passed down the hierarchy. That means less programming is required when adding functions to complex systems. Additional code may then be added to create a more specialized version of the class. If a step is added at the bottom of a hierarchy, then only the processing and the data associated with that unique step needs to be added. Everything else about that step is inherited. The ability to reuse existing objects is considered a major advantage of object technology.

Let’s take the Vehicles as examples.

Bikes and motorcycles are the subclasses from the two-wheeler vehicle, which acts as the base class for them. But two-wheeler vehicle class is the subclass to the class Vehicle. Each lower level in the hierarchy takes the characteristics of the ones before and add more specialized functions for its own.

Screenshot (37)

Encapsulation

Encapsulation is known as “data hiding” concept because it makes an object look like a black box. Acting as concealing the functionality of a class so that the internal operations are hidden from the programmer, encapsulation ensures that the users of an object cannot change the internal state of the object in unexpected ways. With correct encapsulation, the developer does not need to understand how the class actually operates in order to communicate with it via its publicly available methods and properties; known as its public interface.

Encapsulation is essential to creating maintainable OOP. When the interaction with an object uses only the publicly available interface of methods and properties, the class of the object becomes a correctly isolated unit. This unit can then be replaced independently to fix bugs, to change internal behavior or to improve functionality or performance.ATM

There are several ways that an encapsulation can be used, as an example we can take the usage of an interface. The interface can be used to hide the information of an implemented class.

For example, in an ATM system, a client accesses his account by only inserting the card into the machine and giving it his password. Then he requests a withdrawal and if there is enough fund, he will get the money, if not his request will be rejected. The user doesn’t know the sequence of functions and operations that happen inside so that his request is fulfilled or not. The ATM is the encapsulated class.

Summary:

Abstraction: the ability of a program to ignore the details of an object’s subclass and work at a more generic level when appropriate.

Polymorphism: the ability of objects belonging to different types to respond to method calls to methods of the same name, each one according to the right type-specific behavior.

Inheritance: Objects can be defined and created that are specialized types of already-existing objects.

Encapsulation: The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its indented functionalities to other classes.

This was briefly about the Object Oriented Programming concepts 😀

For any feedback or questions, you’re more than welcome to send me an email at yasmine.abdelhady@hotmail.com or reach me @yasabdelhady on twitter.

 

The Object and The Class

Object-Oriented Programming is grouped as self-sustainable “objects”. In order to understand the object orientation clearly, let’s take your “eye” as an example. The “eye” is a class. You have two instances of this object. The first one is named ‘right eye’ and the second is named as the ‘left eye’. Their main functions are controlled and managed by a set of signals sent through your brain, which is in our case the interface. So the brain is the interface which your body uses to interact with your eyes. The ‘eye’ is a class. This ‘eye’ class is being reused to create the left eye and the right eye by changing some of its own properties.

What is an Object in terms of programming?

An object is something can perform a set of related activities. These set of activities that the object performs defines the object’s behavior. For example, the eye can blink. Variables are used to store an Objects identity and state methods are used to show its behavior.

Objects examples: car, student, and table.

In the terminology of OOP, an object is an instance of a class.

What is a class?

Classes are blueprints for objects

A class is simply a representation of a type of object. It is the template that describe the details of an object. It’s the blueprint from which the individual object is created (instantiated).

Several objects have a common state and behavior and thus can be grouped under a single class.

For example a Mercedes, a Ford and a Toyota can be grouped together under the class Car

Class components:

  1. A name
  2. Set of attributes
  3. Methods

ImageName: Car

Set of attributes: Make, Model

These set of attributes that its values are the ones distinguishing a car form another

Methods: Driving, Accelerating, and breaking

These operations or methods are a description of how this car operates and behaves

C# Example of class Car:

public class Car
{
  private string make;
  private int year;

  public car(_make, _year)
  {
      make =_make;
      year = _year;
  }
}

Object references:

When we work with an object we are using a reference to that object. On the other hand, when we are working with simple data types such as Integer, we are working with actual value rather than a reference.

When we create a new object using the ‘new’ keyword, we store a reference to that object in a variable.

For instance:

Car firstCar = new Car ( Honda, 2014 );

This code creates a new instance of car. We gain access to this new object via the firstCar variable. This variable holds reference to the object.

According to the example we can say that the car object, named firstCar, is created out of the Car class with the make ‘Honda’ and the year ‘2013’.

In the real world, you’ll often find many individual objects all of the same kind. As mentioned before, a Honda, a Mercedes, a Ford, and a Toyota can be all created from the class Car. Each car will build its own blueprint. In object oriented terms, we say that the ‘firstCar’ object is an instance of the class of objects known as Car.

Object Oriented Programming

Image

Object Oriented Programming

What?

Object Oriented Programming (OOP) is a computer-programming methodology that emphases on data items rather than processes. Traditionally, software development models are based on a top-down approach, which starts with a functional description of a system and then refined until implementation is achieved.

As Computers increase in processing power, the software they execute becomes more complex. This increase of complexity comes at cost of large programs with huge codebases that quickly become difficult to understand, maintain and keep bug-free.

OOP tries to ease this problem by creating linkages between objects. It focuses first on data items (objects) that are being manipulated. The emphasis is on characterizing data items as active entities, which can perform operations on and for themselves. It then describes how system behavior is implemented through the interaction of the data items.

Why?

OOP provides advantages over traditional structural programming languages:

Real-world modeling

Since it’s a real world modeling, let’s define it with a book as an example. A book is an object that has specific attributes, such as title and author. Using OOP principles, you would model the book as a book object in C# that would have the same properties (as attributes). Creating applications that model real world closely enables developers to understand an application faster than any other application. Therefore, an application that implements OOP concepts effectively is implemented and used.

Promotes the reuse of code

Reuse of code is another advantage OOP provides. The code used to define an object can be shared by several objects of an application. For example the code used to design a type of book can be used for designing different types of books. It works as a template and this saves you from rewriting code for various types of books. A benefit of code reuse is that it reduces the amount of code to write, debug, test, and possibly upgrade in the future.

Provides flexibility in the modifications of an existing application

OOP supports flexibility in the design and implementation of a solution. Maintenance and upgrades are seen as further cycles in application development. By using OOP practices, applications become easier to extend. Consider an example of ABC Corporation. The application used by the production department of this organization is currently designated to create two types of chairs, plastic and metal. To meet the demands of its customers, the organization decides to produce wooden chairs as well. To meet the change in the requirement, the ABC Corporation needs to incorporate changes into its current application system. If the current system was built using OOP best practices, extensions to the system may be simplified. For example the new chair type would be able to share or reuse some of the other chair types’ code. This is due to the previous advantage, which is the reuse of the code.

Helps with the maintenance of code

Last but not least, OOP helps in the maintenance of code. By using OOP, you can create separate components for different requirements. In OOP, a component is known as a class. For example, to design a payroll system of an organization, you could create classes such as Employee and Payroll. By creating the Employee and the Payroll classes, information related to each class can be segregated. An internal change in one of these classes should not affect the functionality of the other class. Therefore, the maintenance of a system is simplified by reducing dependencies in between classes.

That’s all for now, wait for more about OOP and its features and concepts in the next post 🙂

For any feedback or questions, you’re more than welcome to send me an email at Yasmine.abdelhady@hotmail.com or reach me @yasabdelhady on twitter.