OOPS CONCEPTS(Interview-Questions-Answers)

1. What is object-oriented programming (OOP)?
ANS :- OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object is created in the program to represent a class. Therefore, an object encapsulates all the features, such as data and behavior that are associated to a class. OOP allows developers to develop modular programs and assemble them as software. Objects are used to access data and behaviors of different software modules, such as classes, namespaces, and sharable assemblies. .NET Framework supports only OOP languages, such as Visual Basic .NET, Visual C# etc.
2. Explain the basic features of OOPs.
ANS :- The following are the four basic features of OOP:
  • Abstraction - Refers to the process of exposing only the relevant and essential data to the users without showing unnecessary information.
  • Polymorphism - Allows you to use an entity in multiple forms.
  • Encapsulation - Prevents the data from unwanted access by binding of code and data in a single unit called object.
  • Inheritance - Promotes the reusability of code and eliminates the use of redundant code. It is the property through which a child class obtains all the features defined in its parent class. When a class inherits the common properties of another class, the class inheriting the properties is called a derived class and the class that allows inheritance of its common properties is called a base class.
3. What is a 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 of objects. It is a template of object.

A class can be defined as the primary building block of OOP. It also serves as a template that describes the properties, state, and behaviors common to a particular group of objects.
A class contains data and behavior of an entity. For example, the aircraft class can contain data, such as model number, category, and color and behavior, such as duration of flight, speed, and number of passengers. A class inherits the data members and behaviors of other classes by extending from them.

4. What is an object?
They are instance of classes. 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.
6. Define Constructors?  

A constructor is a member function in a class that has the same name as its class. The constructor is automatically invoked whenever an object class is created. It constructs the values of data members while initializing the class.

7. Static Constructor ?

When we declared constructor as static it will be invoked only once for any number of instances of the class and it’s during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.

 using System;
namespace ConsoleApplication3
{
       class Sample
      {
            public string param1, param2;
            static Sample()
           {
                   Console.WriteLine("Static Constructor");
           }
            public Sample()
           {
                   param1 = "Sample";
                   param2 = "Instance Constructor";
            }
       }
       class Program
       {
              static void Main(string[] args)
             {
                 // Here Both Static and instance constructors are invoked for first instance
                  Sample obj=new Sample();
                  Console.WriteLine(obj.param1 + " " + obj.param2);
                   // Here only instance constructor will be invoked
                    Sample obj1 = new Sample();
                    Console.WriteLine(obj1.param1 +" " + obj1.param2);
                    Console.ReadLine();
                }
          }
    }
When we run above program we will get output like as shown below

Output

Static Constructor
Sample Instance Constructor
Sample Instance Constructor

Importance points of static constructor

-      Static constructor will not accept any parameters because it is automatically called by CLR.
-      Static constructor will not have any access modifiers.
-      Static constructor will execute automatically whenever we create first instance of class
-      Only one static constructor will allowed.
-  A static constructor does not take access modifiers or have parameters.
-  A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. 
-  A static constructor cannot be called directly.
-  The user has no control on when the static constructor is executed in the program. 
 A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
The static constructor for a class executes after the static field initializers (if any) for the class.

8. Constructor Overloading
C# supports overloading of constructors, that means, we can have constructors with different sets of parameters. So, our class can be like this:

        public class mySampleClass
       {
                public mySampleClass()
                {
                      // This is the no parameter constructor method.
                     // First Constructor
                 }

                 public mySampleClass(int Age)
                 {
                       // This is the constructor with one parameter.
                       // Second Constructor

                 }

                 public mySampleClass(int Age, string Name)
                {
                      // This is the constructor with two parameters.
                     // Third Constructor
                 }

                  // rest of the class members goes here.
        }

Well, note here that call to the constructor now depends on the way you instantiate the object. For example:

mySampleClass obj = new mySampleClass()
// At this time the code of no parameter constructor (First Constructor)will be executed

mySampleClass obj = new mySampleClass(12)
// At this time the code of one parameter constructor(Second Constructor) will be
// executed.
The call to the constructors is completely governed by the rules of overloading here.

9. Calling Constructor from another Constructor

You can always make a call to one constructor from within another. Say, for example:

public class mySampleClass
{
    public mySampleClass(): this(10)
    {
        // This is the no parameter constructor method.
        // First Constructor
    }

    public mySampleClass(int Age)
    {
        // This is the constructor with one parameter.
        // Second Constructor
    }
}

Very first of all, let us see what is this syntax:

public mySampleClass(): this(10)

Here, this refers to same class, so when we say this(10), we actually mean execute the public mySampleClass(int Age) method. The above way of calling the method is called initializer. We can have at the most one initializer in this way in the method.
Another thing which we must know is the execution sequence i.e., which method will be executed when. Here, if I instantiate the object as:

mySampleClass obj = new mySampleClass()

Then the code of public mySampleClass(int Age) will be executed before the code of mySampleClass(). So, practically the definition of the method:

public mySampleClass(): this(10)
{
    // This is the no parameter constructor method.
    // First Constructor
}

is equivalent to:

public mySampleClass()
{
    mySampleClass(10)
    // This is the no parameter constructor method.
    // First Constructor
}

Note: Above (just above this line) code is mentioned there for pure analogy and will not compile. The intention here is to tell the flow of execution if initializers are used.
We cannot make an explicit call to the constructors in C#, treating them as if any simple method, for example: statement mySampleClass(10) in the above code will not work. The only way you can call one constructor from another is through initializers.
For the VB.NET programmers: you can make the call to another constructor of the same class by the syntaxMe.New(param list), but it should be the first line of your calling constructor method. So ultimately, the code of the called constructor runs prior to the code of the calling constructor, which is same as initializers here.
Note that only this and base (we will see it further) keywords are allowed in initializers, other method calls will raise an error.
This is sometimes called Constructor chaining.

10. Behavior of Constructors in Inheritance

Let us first create the inherited class.

public class myBaseClass
{
    public myBaseClass()
    {
        // Code for First Base class Constructor
    }

    public myBaseClass(int Age)
    {
        // Code for Second Base class Constructor
    }

    // Other class members goes here
}

public class myDerivedClass : myBaseClass
// Note that I am inheriting the class here.
{
    public myDerivedClass()
    {
        // Code for the First myDerivedClass Constructor.
    }

    public myDerivedClass(int Age):base(Age)
    {
        // Code for the Second myDerivedClass Constructor.
    }

    // Other class members goes here
}

Now, what will be the execution sequence here:
If I create the object of the derived class as:

myDerivedClass obj = new myDerivedClass()

Then the sequence of execution will be:
1.       public myBaseClass() method.
2.       and then public myDerivedClass() method.
Note: If we do not provide initializer referring to the base class constructor then it executes the no parameter constructor of the base class.
Note one thing here: we are not making any explicit call to the constructor of base class neither by initializer nor by the base keyword, but it is still executing. This is the normal behavior of the constructor.
If I create an object of the derived class as:

myDerivedClass obj = new myDerivedClass(15)

Then the sequence of execution will be:
1.       public myBaseClass(int Age) method
2.       and then public myDerivedClass(int Age) method
Here, the new keyword base has come into picture. This refers to the base class of the current class. So, here it refers to the myBaseClass. And base(10) refers to the call to myBaseClass(int Age) method.
Also note the usage of Age variable in the syntax: public myDerivedClass(int Age):base(Age). [Understanding it is left to the reader].


No comments:

Post a Comment