Abstraction

This is the fourth principle of  object oriented programming. Abstraction is a concept related to polymorphism. Abstraction in programming means declaring the methods that will be defined in derived class. The idea of abstraction works well with large and complex projects,  where class contains multiple methods that performs different tasks.

Another approach to this concept is saying that Abstraction works by establishing a level of complexity on which a person interacts with the system, suppressing the more complex details below the current level. The process of abstraction is the process to build a software model that presents solution for some task\s in real world. Abstraction is  a process of building concept model of more complex system where we dont need to know how low level tasks are executed

Abstract Base Class

The abstract modifier indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events.  Abstract classes are created to be a base class of other classes. User can not instantiate object and call abstract class method. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.

Lets take a look at example:

 abstract class car
    {
        public abstract void move();
    }

Here we create abstract class with one abstract method. This method must be public so it’s available for other classes.

 abstract class car
    {
        public abstract void move();
    }
    class audi : car
    {
        public override void move()
        { 
             Console.WriteLine("moving"); 
        }
    }

Method in child class must overwrite the abstract method and contain the body of the function. Noticed that abstract class contains only declaration of the method.

class audi : car
        {
            public override void move() { Console.WriteLine("moving"); }
        }
        static void Main(string[] args)
        {
            audi r8 = new audi();
            car myNewCar = r8;
            myNewCar.move();
            r8.move();
        }
    }

We can now call our method from the instance of the child class. We can also create Object of type car, by coping the instance of subclass. Notice that we don’t instantiate object of abstract class.

This was the last topic of main principles of object oriented programming in C#. In the next article I’ll cover more complex topics. Use this knowledge to write better and more cleaner code. Posts about other principles of oop you can find in C# .NET category. Stay Awesome!

 

Encapsulation

Encapsulation, also known as information hiding, Is  the procedure of covering up of data and functions into a single class. Encapsulation is used to prevent the user of a given class from manipulating objects in ways that are not intended by the designer. This can be achieved by restricting access to the members. Unprotected data is vulnerable to accidental corruption due to the errors in other parts of program.

Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member. Those are  ways to specify access in C#:

  • Public: Access to all code in the program
  • Private: Access to only members of the same class
  • Protected: Access to members of same class and its derived classes
  • Internal: Access to current assembly
  • Protected Internal: Access to current assembly and types derived from containing class

Public Access Specifiers

Public class member can be accessed by other class member that is initialized outside the class. A public member can be accessed from anywhere even outside the namespace. Public access specifier allows a class to expose its member variables and member functions to other functions and objects, this way methods can be called from outside of the class with declaration.

using System;

 class PublicAccess
 {
 // Public string 
 public string word;
 // Public method
 public void print()
 {
 Console.WriteLine("Selected word: " + word);
 }
 }
//Other Class
 class Program
 {
 static void Main(string[] args)
 {
 //Creating instance of the object
 PublicAccess ac = new PublicAccess();
 Console.Write("Chose word:");
 // Calling methods form instance
 ac.word = Console.ReadLine();
 ac.print();
 Console.ReadLine();
 }
 }

In this example user can change the value of the string variable and can call method from instance of the object.

Private Access Specifiers

Changing variable specifier to private restricts its accessibility , by hiding it from other classes. After changing string variable from first example to private we an no longer call its name in the instance.

private string word;
//here we will have a compiler error
ac.word
//We can still call our method 
ac.print();

This example shows how to restrict access to variables and prevent other classes from accidentally changing it value.

Protected Access Specifiers

Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance. You can read my article about Inheritance, here.

Now, in our example we change the specifier to protected.

protected string word;

The outcome is the same as in  private version. But now we can create class that inherit from main class, and we can change value of the variable from there.

using System;
//New class that inherits from previous class  
  class Program : PublicAccess 
   {
     static void Main(string[] args)
      {
        Program p=new Program();
        Console.Write("Chose Word:");
        p.name = Console.ReadLine(); 
        p.print();
        Console.ReadLine();
      }
   }

Now we don’t have any errors, and we can change the value of the variable

Internal Access Specifier

It is the default access specifiers for a class in C# programming. With this property any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.

In our example output is the same as in public variable, because both classes exists in same application.

Protected Internal Access

The protected internal access specifier allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application.  The protected internal access specifier allows its members to be accessed in derived class, containing class or classes within same application. This the type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

In other words the type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

 

 

 

In this article I presented you all possible implementations of encapsulation. This concept goes well together with inheritance. Protecting variables can prevent a code from corruption and save many hour of debugging. In next article I’ll present last major principle of object oriented programming, abstraction. Have fun with this new concepts. Stay Awesome!

Polymorphism

In last post I described Inhabitance, one of four major principles of object oriented programming. Today we will take a look at Polymorphism, second equally important principle.

Polymorphism (from Greek  polys, “many, much” and morphē, “form, shape”)  describes process of using once declared method in many forms. This action is possible thanks to incarcerate.  Polymorphism have two main kinds: dynamic and static. Static polymorphism is the mechanism of linking a function with an object during compile time. Most important thing about static polymorphism is Function Overloading

Function Overloading

This tool can be used to change the number and types of arguments. that are passed to the function. This extends the functionality of the method. Is commonly used in declaring a class constructors. Let’s take a look at example.

using System;
 class Print
 {
 void print(int i)
 {
 Console.WriteLine("Printing int: {0}", i);
 }
// Function can be overloaded with different argument.
 void print(double f)
 {
 Console.WriteLine("Printing float: {0}", f);
 }
//Function can be also overloaded with many arguments.
 void print(int i, string s)
 {
 Console.WriteLine("Printing int: {0} and string: {1}",i, s);
 }
 static void Main(string[] args)
 {
 Print newfunction = new Print();
 newfunction.print(5);
 newfunction.print(500.263);
 newfunction.print(5, "Hello C++");
 Console.ReadKey();
 }
 }

Body of the function can be different for each method, that’s  why it can be so useful to  improve the usability of the code.

Overriding 

Another type of Polymorphism is  overriding,  also called run-time polymorphism.

This action is performed by using key word override. It is used to change the body of the method declared in parent class. This way we can use method with exactly the same name for different purposes. In this simple example we will override method for writing a line of code.

using System;

public class Line : DrawingObject
{
 public override void Draw()
 {
 Console.WriteLine("I'm a Line.");
 }
}

public class Circle : DrawingObject
{
 public override void Draw()
 {
 Console.WriteLine("I'm a Circle.");
 }
}

public class Square : DrawingObject
{
 public override void Draw()
 {
 Console.WriteLine("I'm a Square.");
 }
}

This way we can loop between all Elements of the same parent class and have different results.

public class DrawDemo
{
 public static int Main()
 {
 DrawingObject[] dObj = new DrawingObject[4];

 dObj[0] = new Line();
 dObj[1] = new Circle();
 dObj[2] = new Square();
 dObj[3] = new DrawingObject();

//Loop that runs for every element of an array.
 foreach (DrawingObject drawObj in dObj)
 {
 drawObj.Draw();
 }
 return 0;
 }
}

In this post I covered basic use of Polymorphism, in the next post we will take brief look at another major concept called Encapsulation. Use this knowledge to experiment and to  build more flexible software and share you results in comments. Stay Awesome!

Inheritance

Today we will take a look at inheritance, one of the four major principles of object oriented programming. Inheritance is used to crate new class based on existing one, which means reuse of properties and method from parent class. It’s important to mention that C# does not support multiple inheritance of classes, but it does support inheritance of multiple interfaces. In c# you can crate chains of connections by inheriting from parent class that inherits from another parent class, this way you can keep properties from multiple classes.

Inheritance is marked by colon( ” : ” ) in the new class declaration, between the name of child class and name of the parent class

class <child_class> : <parent_class>
{
  //class body
}

 

Lets take a look at example of simple implementation

using System;
namespace InheritanceApplication
{

 //Parent Class
 class Shape
 {
 //Values of parent class should be protected 
 //so it can not be overriten in child class
 protected int side;
 public void setBase(int a)
 {
 side = a;
 } 
 }

 // Child class
 class Square : Shape
 {
 public int getArea()
 {
 return (side * side);
 }
 }

 class MainClass
 {
 static void Main(string[] args)
 {
 Square Box = new Square();
 //Method from parent class
 Box.setBase(5);
 //Method from child class
 Box.getArea();

 // Print the area of the square.
 Console.WriteLine("Total area: " + Box.getArea());
 Console.ReadKey();
 }
 }
}

We can see that we can use methods from both classes. We used the protected keyword because the accessibility of a member in the child class depends upon its declared accessibility in the parent class.

Creating child class is useful when we want to extend functionality of existing class without changing it(part of SOLID design). Child class can overwrite the methods from parent class, by rewriting the method declaration. But this is part of another key principle of oop called Polymorphism. We will take a look on this in next post. Stay Awesome!

 

 

 

.