OOPS Basics


OOPS is a programming paradigm/Model/standard based on the concept of "objects". It is a problem solving technique to develop software systems. 
(It is a technique to think real world in terms of objects. These objects have responsibilities and provide services to application or other objects.)



Object: -It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Attributes and behavior of an object are defined by the class definition. They are instance of classes.

Class: - A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects. It is a comprehensive data type, which represents a blue print (template) of objects. 

(Note: - Class is a definition, while object is an instance of the class created. Class is a blue print while objects are actual objects existing in real world.)

Structure: - A structure type is a value type that is typically used to encapsulate small groups of related variables. The struct keyword is used for creating a structure. Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book:

Example:-
        struct Books
        {
            public string title;
            public string author;
            public string subject;
            public int book_id;
        }; 



            Class Vs Structure:-
                      Similarities:-
  • Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
  • Structures and classes can implement interface.
  • Both of them can have constructors with and without parameter.
  • Both can have delegates and events.
                      Differences:-
  • Structures are value types and classes are reference types. So structures use stack and classes use heap.
  • Structs can implement an interface but they cannot inherit from another struct. For that reason, struct members cannot be declared as protected.
  • Structures members cannot be declared as protected, but class members can be.
  • You cannot do inheritance in structures.
  • Structures do not require constructors while classes require.
  • Objects created from classes are terminated using Garbage collector. Structures are not destroyed using GC.
Constructors are class methods that are executed when an object of a given type is created. Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read. 

If do not provide a constructor for your object, C# will create one by default that instantiates the object and sets member variables to the default values.

Shared (VB.NET)/Static(C#) Variables: - Static/Shared classes are used when a class provides functionality, which is not specific to any instance. In short, if you want an object to be shared between multiple instances you will use a static/Shared class.

Following are features of Static/Shared classes:-
  • They cannot be instantiated. By default, an object is created on the first method call to that object.
  • Static/Shared classes cannot be inherited.
  • Static/Shared classes can have only static members.
  • Static/Shared classes can have only static constructor.


There are four major pillars of Object Oriented Programming: -
  • Abstraction: - Abstraction is a process of exposing essential features of an entity by hiding the other irrelevant details. Abstraction mainly reduces complexity and increases efficiency. An entity can have multiple abstractions. It allows complex real world to be represented in simplified manner. For example color is abstracted to RGB. By just making the combination of these three colors we can achieve all color.
    • We cannot create an object of abstract class.
    • Abstract class is designed to act as a base class (to be inherited by other classes).
    • Abstract class is a design concept in program development and provides a base upon which other classes are built.
    • Abstract classes are similar to interfaces. After declaring an abstract class, it cannot be instantiated on its own, it must be inherited.

     
  • Encapsulation: - Encapsulation is the process of putting data and the operations (functions) that can be performed on that data into a single container called class. Now, any programmer can use this class without knowing how it is implemented. Due to encapsulation, data is insulated, thus not directly accessible from the outside world. It is a process of hiding all the internal details of an object from the outside world. (Remember, Encapsulation is not data hiding, but, Encapsulation leads to data hiding.) 


    Encapsulation is sometimes referred to as the first pillar or principle of OOPS. According to the principle of encapsulation, a class or struct can specify how accessible each of its members is to code outside of the class or struct. Methods and variables that are not intended to be used from outside of the class or assembly can be hidden to limit the potential for coding errors or malicious exploits.

  • Inheritance: - Inheritance is a process of creating new class from the existing one. The new class may have some additional properties and functionality. Hierarchy is used to define more specialized classes based on a preexisting generalized class.

    Example: - we have VEHICLE class and we can inherit this class make more specialized class like CAR, which will add new attributes and use some existing qualities of the parent class. Its shows more of a parent-child relationship. This kind of hierarchy is called inheritance.
    The idea of inheritance implements the IS-A relationship. For example, mammal IS Animal, dog IS-A mammal hence dog IS-A animal as well, and so on.

     
  • Polymorphism: -Poly means many and Morphs means forms. Polymorphism refers to the ability to take multiple forms and it allows us to invoke derived class methods through a base class reference during run-time. When inheritance is used to extend a generalized class to a more specialized class, it includes behavior of the top class (Generalized class). The inheriting class often implements a behavior that can be somewhat different than the generalized class, but the name of the behavior can be same.

    There are two types of polymorphism:
    • Static or compile time polymorphism (Method overloading)
    • Dynamic or runtime polymorphism (Method overriding) 
  • Static or Compile Time Polymorphism
    • In static polymorphism, the decision is made at compile time.
    • Which method is to be called is decided at compile-time only.
    • Method overloading is an example of this.
    • Compile time polymorphism is method overloading, where the compiler knows which overloaded method it is going to call.
    • Method overloading is a concept where a class can have more than one method with the same name and different parameters.
    • Compiler checks the type and number of parameters passed on to the method and decides which method to call at compile time and it will give an error if there are no methods that match the method signature of the method that is called at compile time.
                Example:-
namespace DotNetLearningArray
{
    class Program
    {
        public class Overloading
        {

            public void Add(string a1, string a2)
            {
                Console.WriteLine("Adding String :" + a1 + a2);
            }

            public void Add(int a1, int a2)
            {
                Console.WriteLine("Adding Integer :" + a1 + a2);
            }

        }

        static void Main(string[] args)
        {
            Overloading obj = new Overloading();

            obj.Add("Mangal ", "Sing");

            obj.Add(3, 7);

            Console.ReadLine();
        }
    }
}

  • Dynamic or Runtime Polymorphism
    • Run-time polymorphism is achieved by method overriding.
    • Method overriding allows us to have methods in the base and derived classes with the same name and the same parameters.
    • By runtime polymorphism, we can point to any derived class from the object of the base class at runtime that shows the ability of runtime binding.
    • Through the reference variable of a base class, the determination of the method to be called is based on the object being referred to by reference variable.
    • Compiler would not be aware whether the method is available for overriding the functionality or not. So compiler would not give any error at compile time. At runtime, it will be decided which method to call and if there is no method at runtime, it will give an error.
              Example:-
namespace DotNetLearningArray
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("It is From Base Class.");
            }
        }

        public class Derived : Base
        {
            public override void Show()
            {
                Console.WriteLine("It is From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBase;
            objBase = new Base();
            objBase.Show();//    Output -It is From Base Class.

            objBase = new Derived();
            objBase.Show();//Output-It is From Derived Class.

            Console.ReadLine();
        }
    }
}
  • Virtual Method: - Virtual method is a method whose behavior can be overridden in derived class. Virtual method allows declare a method in base class that can be redefined in each derived class. When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.
    • By default, methods are non-virtual. You cannot override a non-virtual method.
    • You cannot use the virtual modifier with the static, abstract, private or override modifiers.
    • Virtual properties behave like abstract methods, except for the differences in declaration and invocation syntax.
    • It is an error to use the virtual modifier on a static property.
    • Virtual methods can't be declared as private.
    • A virtual property or method has an implementation in the base class, and can be overridden in the derived classes.
    • A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
    When a virtual method is called on a reference, the actual type of the object to which the reference refers is used to determine which method implementation should be used. When a method of a base class is overridden in a derived class (subclass), the version defined in the derived class is used. This is so even should the calling application be unaware that the object is an instance of the derived class.
               Example:- 
namespace DotNetLearningArray
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("It is From Base Class.");
            }
        }

        public class Derived : Base
        {
            //the keyword "override" change the base class method.
            public override void Show()
            {
                Console.WriteLine("It is From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseRefToDerived = new Derived();
            objBaseRefToDerived.Show();//Output-It is From Derived Class.

            Console.ReadLine();
        }
    }
}

  • Shadowing (Method Hiding)
    When two elements in a program have same name, one of them can hide and shadow the other one. So in such cases the element, which shadowed the main element, is referenced. Shadowing hides a method in a base class. 
    (Creating an entirely new method with the same signature as one in a base class)
Example:-
class A
{
    public int Foo() { return 5; }
    public virtual int Bar() { return 5; }
}
class B : A
{
    public new int Foo() { return 1; }
    public override int Bar() { return 1; }
}

Class B overrides the virtual method Bar. It hides (shadows) the non-virtual method Foo. Override uses the override keyword. Shadowing is done with the new keyword. In the code above, if you didn't use the new keyword when defining the Foo method in class B, you would get compiler warning.

Method hiding does not have a relationship between the methods in the base class and derived class. The method in the derived class hides the method in the base class.

        Example:-
namespace DotNetLearningArray
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("It is From Base Class.");
            }
        }

        public class Derived : Base
        {

            public new void Show()
            {
                Console.WriteLine("It is From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseRefToDerived = new Derived();
            objBaseRefToDerived.Show();//Output-It is From Base Class.

            Console.ReadLine();
        }
    }
}

The C# language specification states that "You cannot override a non-virtual method."


  • Sealed Keyword: - Sealed keyword can be used to stop method overriding in a derived classes.
    By default, all methods are sealed, which means you can't override them, so that "sealed" keyword is redundant in this case and compiler will show you an error when you'll try to make sealed already sealed method. But if your method was marked as virtual in a base class, by overriding and marking this method with "sealed" will prevent method overriding in derived classes
           Example:-
namespace DotNetLearningArray
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("This is Base Class.");
            }
        }

        public class Derived : Base
        {
            public override sealed void Show()
            {

                Console.WriteLine("This is Derived Class.");
            }
        }

        static void Main(string[] args)
        {
            Base objBaseReference = new Derived();
            objBaseReference.Show();// Output-This is Derived Class.

            Console.ReadLine();
        }
    }
}


  • Interface: -An interface contains definitions for a group of related functionalities that a class or a struct can implement.  By using interfaces, you can, for example, include behavior from multiple sources in a class. For details please refer my blog, Abstract Classes and Interface in C#


Comments