Showing posts with label D - Object Oriented. Show all posts
Showing posts with label D - Object Oriented. Show all posts

Tuesday, 20 May 2014

D - Abstract Classes

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

D - Abstract Classes

Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class.
If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclass. This is typically how abstract classes come about during the design phase. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own.

Abstract Class

Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration somewhere before the class keyword. The following shows an example of how abstract class can be inherited and used.
import std.stdio;
import std.string;
import std.datetime;

abstract class Person
{
   int birthYear, birthDay, birthMonth;
   string name;
   int getAge()
   {
       SysTime sysTime = Clock.currTime();
       return sysTime.year - birthYear;
   }
}

class Employee : Person
{
   int empID;
}

void main()
{
   Employee emp = new Employee();
   emp.empID = 101;
   emp.birthYear = 1980;
   emp.birthDay = 10;
   emp.birthMonth = 10;
   emp.name = "Emp1";
   writeln(emp.name);
   writeln(emp.getAge);
}
When we compile and run the above program, we will get the following output.
Emp1
34

Abstract functions

Similar to functions, classes can also be made abstract. The implementation of such function is not given in its class but should be provided in the class that inherits the class with abstract function. A above example is updated with abstract function and is given below.
import std.stdio;
import std.string;
import std.datetime;

abstract class Person
{
   int birthYear, birthDay, birthMonth;
   string name;
   int getAge()
   {
       SysTime sysTime = Clock.currTime();
       return sysTime.year - birthYear;
   }
   abstract void print();
}

class Employee : Person
{
   int empID;

   override void print()
   {
      writeln("The employee details are as follows:");
      writeln("Emp ID: ", this.empID);
      writeln("Emp Name: ", this.name);
      writeln("Age: ",this.getAge);
   }
}

void main()
{
   Employee emp = new Employee();
   emp.empID = 101;
   emp.birthYear = 1980;
   emp.birthDay = 10;
   emp.birthMonth = 10;
   emp.name = "Emp1";
   emp.print();
}
When we compile and run the above program, we will get the following output.
The employee details are as follows:
Emp ID: 101
Emp Name: Emp1
Age: 34

Posted By MIrza Abdul Hannan4:34:00 pm

D - Encapsulation And D - Interfaces

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

D - Encapsulation

All D programs are composed of the following two fundamental elements:
  • Program statements (code): This is the part of a program that performs actions and they are called functions.
  • Program data: The data is the information of the program which affected by the program functions.
Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.
D supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private, protected and publicmembers. By default, all items defined in a class are private. For example:
class Box
{
   public:
      double getVolume()
      {
         return length * breadth * height;
      }
   private:
      double length;      // Length of a box
      double breadth;     // Breadth of a box
      double height;      // Height of a box
};
The variables length, breadth, and height are private. This means that they can be accessed only by other members of the Box class, and not by any other part of your program. This is one way encapsulation is achieved.
To make parts of a class public (i.e., accessible to other parts of your program), you must declare them after the public keyword. All variables or functions defined after the public specifier are accessible by all other functions in your program.
Making one class a friend of another exposes the implementation details and reduces encapsulation. The ideal is to keep as many of the details of each class hidden from all other classes as possible.

Data Encapsulation Example:

Any D program where you implement a class with public and private members is an example of data encapsulation and data abstraction. Consider the following example:
import std.stdio;

class Adder{
   public:
      // constructor
      this(int i = 0)
      {
        total = i;
      }
      // interface to outside world
      void addNum(int number)
      {
          total += number;
      }
      // interface to outside world
      int getTotal()
      {
          return total;
      };
   private:
      // hidden data from outside world
      int total;
}
void main( )
{
   Adder a = new Adder();

   a.addNum(10);
   a.addNum(20);
   a.addNum(30);

   writeln("Total ",a.getTotal());
}
When the above code is compiled and executed, it produces the following result:
Total 60
Above class adds numbers together, and returns the sum. The public members addNum and getTotalare the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world, but is needed for the class to operate properly.

Designing Strategy:

Most of us have learned through bitter experience to make class members private by default unless we really need to expose them. That's just good encapsulation.
This wisdom is applied most frequently to data members, but it applies equally to all members, including virtual functions.

D - Interfaces

An interface is a way of forcing the classes that inherit from it to have to implement certain functions or variables. Functions must not be implemented in an interface because they are always implemented in the classes that inherit from the interface. An interface is created using the interface keyword instead of the class keyword even though the two are similar in a lot of ways. When you want to inherit from an interface and the class already inherits from another class then you need to separate the name of the class and the name of the interface with a comma.
Let us look at an simple example that explains the use of an interface.
import std.stdio;

// Base class
interface Shape
{
   public:
      void setWidth(int w);
      void setHeight(int h);
}

// Derived class
class Rectangle: Shape
{
   int width;
   int height;
   public:
      void setWidth(int w)
      {
         width = w;
      }
      void setHeight(int h)
      {
         height = h;
      }

      int getArea()
      {
         return (width * height);
      }
}

void main()
{
   Rectangle Rect = new Rectangle();

   Rect.setWidth(5);
   Rect.setHeight(7);

   // Print the area of the object.
   writeln("Total area: ", Rect.getArea());

}

When the above code is compiled and executed, it produces the following result:
Total area: 35

Interface with Final and Static Functions

An interface can have final and static method for which definitions should be included in interface itself. These functions cannot be over-riden by the derived class. A simple example is shown below.
import std.stdio;

// Base class
interface Shape
{
   public:
      void setWidth(int w);
      void setHeight(int h);
      static void myfunction1()
      {
         writeln("This is a static method");
      }
      final void myfunction2()
      {
         writeln("This is a final method");
      }
}

// Derived class
class Rectangle: Shape
{
   int width;
   int height;
   public:
      void setWidth(int w)
      {
         width = w;
      }
      void setHeight(int h)
      {
         height = h;
      }

      int getArea()
      {
         return (width * height);
      }
}

void main()
{
   Rectangle rect = new Rectangle();

   rect.setWidth(5);
   rect.setHeight(7);

   // Print the area of the object.
   writeln("Total area: ", rect.getArea());
   rect.myfunction1();
   rect.myfunction2();
}
When the above code is compiled and executed, it produces the following result:
Total area: 35
This is a static method
This is a final method

Posted By MIrza Abdul Hannan4:33:00 pm

D - Overloading

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

D - Overloading

D allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively.
An overloaded declaration is a declaration that had been declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most appropriate definition to use by comparing the argument types you used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution.

Function overloading

You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You can not overload function declarations that differ only by return type.
Following is the example where same function print() is being used to print different data types:
import std.stdio;
import std.string;
class printData
{
   public:
      void print(int i) {
         writeln("Printing int: ",i);
      }

      void print(double  f) {
        writeln("Printing float: ",f );
      }

      void print(string s) {
        writeln("Printing string: ",s);
      }
};

void main()
{
   printData pd = new printData();

   // Call print to print integer
   pd.print(5);
   // Call print to print float
   pd.print(500.263);
   // Call print to print character
   pd.print("Hello D");
}
When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500.263
Printing string: Hello D

Operators overloading

You can redefine or overload most of the built-in operators available in D. Thus a programmer can use operators with user-defined types as well.
Operators can be overloaded using string op followed by Add, Sub and so on based on the operator that is being overloaded. We can overload the operator + to add two boxes as shown below.
Box opAdd(Box b)
{
   Box box = new Box();
   box.length = this.length + b.length;
   box.breadth = this.breadth + b.breadth;
   box.height = this.height + b.height;
   return box;
}
Following is the example to show the concept of operator over loading using a member function. Here an object is passed as an argument whose properties will be accessed using this object, the object which will call this operator can be accessed using this operator as explained below:
import std.stdio;

class Box
{
   public:

      double getVolume()
      {
         return length * breadth * height;
      }
      void setLength( double len )
      {
         length = len;
      }

      void setBreadth( double bre )
      {
         breadth = bre;
      }

      void setHeight( double hei )
      {
         height = hei;
      }

      Box opAdd(Box b)
      {
         Box box = new Box();
         box.length = this.length + b.length;
         box.breadth = this.breadth + b.breadth;
         box.height = this.height + b.height;
         return box;
      }
   private:
      double length;      // Length of a box
      double breadth;     // Breadth of a box
      double height;      // Height of a box
};
// Main function for the program
void main( )
{
   Box box1 = new Box();    // Declare box1 of type Box
   Box box2 = new Box();    // Declare box2 of type Box
   Box box3 = new Box();    // Declare box3 of type Box
   double volume = 0.0;     // Store the volume of a box here

   // box 1 specification
   box1.setLength(6.0);
   box1.setBreadth(7.0);
   box1.setHeight(5.0);

   // box 2 specification
   box2.setLength(12.0);
   box2.setBreadth(13.0);
   box2.setHeight(10.0);

   // volume of box 1
   volume = box1.getVolume();
   writeln("Volume of Box1 : ", volume);

   // volume of box 2
   volume = box2.getVolume();
   writeln("Volume of Box2 : ", volume);

   // Add two object as follows:
   box3 = box1 + box2;

   // volume of box 3
   volume = box3.getVolume();
   writeln("Volume of Box3 : ", volume);

}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

Posted By MIrza Abdul Hannan4:30:00 pm