Showing posts with label polymorphism. Show all posts
Showing posts with label polymorphism. Show all posts

Monday, March 25, 2013

OOps interview Questions

OOps interview Questions


1) What is meant by Object Oriented Programming? 

     OOP is a method of programming in which programs are organised as cooperative collections of objects. Each object is an instance of a class and each class belong to a hierarchy.

2) What is a Class? 
     Class is a template for a set of objects that share a common structure and a common behaviour. The keyword class in C# indicates that we are going to define a new class (type of object)

3) What is an Object? 

   Object is anything that is identifiable as a single material item.  Object is an instance of a class. It has state,behaviour and identity. It is also called as an instance of a class.  

4) What is an Instance? 

     An instance has state, behaviour and identity. The structure and behaviour of similar classes are defined in their common class. An instance is also called as an object.

5) What are the core OOP’s concepts? 

     Abstraction, Encapsulation,Inheritance and Polymorphism are the core OOP’s concepts.

6) What is meant by abstraction? 

     Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. Its the process of focussing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model.

7) What is meant by Encapsulation? 

     Encapsulation is the process of compartmentalising the elements of an abtraction that defines the structure and behaviour. Encapsulation helps to separate the contractual interface of an abstraction and implementation.

8) What is meant by Inheritance? 

  It provides a convenient way to reuse existing fully tested code in different context thereby saving lot of coding. Inheritance is a relationship among classes, wherein one class shares the structure or behaviour defined in another class. This is called Single Inheritance. If a class shares the structure or behaviour from multiple classes, then it is called Multiple Inheritance. Inheritance defines “is-a” hierarchy among classes in which one subclass inherits from one or more generalised superclasses.

9) What is meant by Polymorphism? 

     Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behavior or value in a subclass, to something that was declared in a parent class.

10) What is an Abstract Class? 

     Abstract class is a class that has no instances. An abstract class is written with the expectation that its concrete subclasses will add to its structure and behaviour, typically by implementing its abstract operations.

There are scenarios in which it is useful to define classes that is not intended to instantiate; because such classes normally are used as base-classes in inheritance hierarchies, we call such classes abstract classes. 

Abstract classes cannot be used to instantiate objects; because abstract classes are incomplete, it may contain only definition of the properties or methods and derived classes that inherit this implements it's properties or methods. 

Static, Value Types & interface doesn't support abstract modifiers. Static members cannot be abstract. Classes with abstract member must also be abstract.


11) What is an Interface? 

An interface is a contract & defines the requisite behavior of generalization of types. 

Interface is an outside view of a class or object which emphaizes its abstraction while hiding its structure and secrets of its behaviour.
An interface mandates a set of behavior, but not the implementation. Interface must be inherited. We can't create an instance of an interface
An interface is an array of related function that must be implemented in derived type. Members of an interface are implicitly public & abstract. An interface can inherit from another interface.
12) What is a base class? 


     Base class is the most generalised class in a class structure. Most applications have such root classes. In Java, Object is the base class for all classes.

13) What is a subclass? 

     Subclass is a class that inherits from one or more classes.

14) What is a superclass? 

     superclass is a class from which another class inherits.

15) What is a constructor? 

     Constructor is an operation that creates an object and/or initialises its state.

16) What is a destructor? 

     Destructor is an operation that frees the state of an object and/or destroys the object itself.

17) What is meant by Binding? 

     Binding denotes association of a name with a class.

18) What is meant by static binding? 

     Static binding is a binding in which the class association is made during compile time. This is also called as Early binding.

19) What is meant by Dynamic binding? 

     Dynamic binding is a binding in which the class association is not made until the object is created at execution time. It is also called as Late binding.

20) Define Modularity? 

     Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.

21) What is meant by Persistence?

     Persistence is the property of an object by which its existence transcends space and time.

22) How to prevent a class from being inherited?

In order to prevent a class in C# from being inherited, the keyword sealed is used. Thus a sealed class may not serve as a base class of any other class. It is also obvious that a sealed class cannot be an abstract class.
//C# Example
sealed class MyClass
{
    public int x;
    public int y;
}
No class can inherit from MyClass defined above. Instances of ClassA may be created and its members may then be accessed.


23) What is Polymorphism?

Polymorphism means one interface and many forms. Polymorphism is a characteristics of being able to assign a different meaning or usage to something in different contexts specifically to allow an entity such as a variable, a function or an object to have more than one form. 

There are two types of Polymorphism. 

Compile time: function or operator overloading 
Runtime: Inheritence & virtual functions


24) What is Abstract method?

Abstract method doesn't provide the implementation & forces the derived class to override the method.

25) What is Virtual method?

Virtual Method allows a  derived class with the option to override it.

25) Can Struct be inherited?

No, Struct can't be inherited as this is implicitly sealed.


26) What is Static field?

To indicate that a field should only be stored once no matter how many instance of the class we create.

27) What is Static Method?

It is possible to declare a method as Static provided that they don't attempt to access any instance data or other instance methods.



28) What is Virtual keyword?

This keyword indicates that a member can be overridden in a child class. It can be applied to methods, properties, indexes and events.


29) What is New modifiers?

The new modifiers hides a member of the base class. C# supports only hide by signature.


30) What is Sealed modifiers?

Sealed types cannot be inherited & are concrete. 
Sealed modifiers can also be applied to instance methods, properties, events & indexes. It can't be applied to static members. 
Sealed members are allowed in sealed and non-sealed classes.

31) When to use Interface over abstract class?

Abstract Classes: Classes which cannot be instantiated. This means one cannot make a object of this class or in other way cannot create object by saying 
ClassAbs abs = new ClassAbs(); where ClassAbs is abstract class. 
Abstract classes contains one or more abstarct methods, ie method body only no implementation. 
Interfaces: These are same as abstract classes only difference is that we can only define method definition and no implementation. 
When to use what depends on various reasons. One being design choice. 
One reason for using abstarct classes is we can code common functionality and force our developer to use it. I can have a complete class but I can still mark the class as abstract. 
Developing by interface helps in object based communication.

32) What is pure virtual function?

When you define only function prototype in a base class without and do the complete implementation in derived class. This base class is called abstract class and client won’t able to instantiate an object using this base class. 

A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be "pure" using the curious "=0" 
syntax: 
class Base { 
public: 
void f1(); // not virtual 
virtual void f2(); // virtual, not pure 
virtual void f3() = 0; // pure virtual 
};


33) Can we specify the access modifier for explicitly implemented interface method?

No, we can't specify the access modifier for the explicitly implemented interface method. By default its scope will be internal.

34) What is Protected access modifier in C#?

The protected keyword is a member access modifier. It can only be used in a declaring a function or method not in the class ie. a class can't be declared as protected class. 

A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declare this member. In other words access is limited to within the class definition and any class that inherits from the class 

A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type. 

35) What is Public access modifier in C#?

The public keyword is an access modifier for types and type members ie. we can declare a class or its member (functions or methods) as Public. There are no restrictions on accessing public members.

36) What is Private access modifier in C#?

The private keyword is a member access modifier ie. we can't explicitly declare a class as Private, however if do not specify any access modifier to the class, its scope will be assumed as Private. Private access is the least permissive access level of all access modifiers. 

Private members are accessible only within the body of the class or the struct in which they are declared. This is the default access modifier for the class declaration. 

37) What is Internal access modifier in C#?

The internal keyword is an access modifier for types and type members ie. we can declare a class as internal or its member as internal. Internal members are accessible only within files in the same assembly (.dll). In other words, access is limited exclusively to classes defined within the current project assembly. 

38 ) What is Protected Internal access modifier in C#?

Protected Internal is a access modifiers for the members (methods or functions) ie. you can't declare a class as protected internal explicitly. The members access is limited to the current assembly or types derived from the containing class. 

Protected Internal means the method is accessible by anything that can access the protected method UNION with anything that can access the internal method. 

39) What all classes bear Default Access modifiers in C#?

a) An enum has default modifier as public 

b) A class has default modifiers as Internal .
 It can declare members (methods etc) with following access modifiers: 
public 
internal 
private 
protected internal 

c) An interface has default modifier as public 

d) A struct has default modifier as Internal .
It can declare its members (methods etc) with following access modifiers: 
public 
internal 
private 

e) A methods, fields, and properties has default access modifier as "Private" if no modifier is specified.


40) What is method overloading?
Method overloading occurs when a class contains two methods with the same name, but different signatures.Method overloading allows us to write different version of the same method in a class or derived class. Compiler automatically select the most appropriate method based on the parameter supplied. 

Example:

public class AddClass

{

    public int Add(int a, int b)

    {

        return a + b;

    }

   public int Add(int a, int b, int c)

    {

        return a+b+c;

    }     

}
To call the above method, you can use following code. 

AddClass ad= new AddClass();

int number = ad.Add(2, 3) // result =5

int number1 = ad.Add(2, 3, 4) // result = 9

Rules for Overloading
There must be changes in either return type,or number of parameters or type of parameters.
You can't have a overload method with same number parameters but different return type. In order to create overload method, the return type must be the same and parameter type must be different or different in numbers.

41) What is Overriding?

Method overriding is a feature that allows to invoke functions (that have the same signatures) and that belong to different classes in the same hierarchy of inheritance using the base class reference. In C# it is done using keywords virtual and override

42) What is Method Overriding? How to override a function in C#?

Use the override modifier to modify a method, a property, an indexer, or an event. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method. 
You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.

43) Can we call a base class method without creating instance?
Yes. But .. 

* Its possible If its a static method. 

* Its possible by inheriting from that class also. 

* Its possible from derived classes using base keyword.


44) In which cases you use override and new base?

Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.

45) Difference between new and override keyword?

Consider the following program. 

using System;

 class Program
    {
        public class BaseClass
        {

            public virtual void func1()
            {

               Console.WriteLine("Base Class function 1.");

            }



            public virtual void func2()
            {

               Console.WriteLine("Base Class function 2.");

            }



            public void func3()
            {

               Console.WriteLine("Base Class function 3.");

            }

        }



        public class DeriveClass : BaseClass
        {

            public new void func1()
            {

               Console.WriteLine("Derieve Class fuction 1 used new keyword");

            }



            public override void func2()
            {

               Console.WriteLine("Derieve Class fuction 2 used override keyword");

            }



            public void func3()
            {

               Console.WriteLine("Derieve Class fuction 3 used override keyword");

            }



        }

        static void Main(string[] args)
        {
            BaseClass b = new BaseClass();

            b.func1();



            DeriveClass d = new DeriveClass();

            d.func1();



            //Calls Base class function 1 as new keyword is used.

            BaseClass bd = new DeriveClass();

            bd.func1();



            //Calls Derived class function 2 as override keyword is used.

            BaseClass bd2 = new DeriveClass();

            bd2.func2();

            Console.Read();

        }
    }




Now the difference is 

new: hides the base class function. 
Override: overrides the base class function. 


BaseClass objB = new DeriveClass();


If we create object like above notation and make a call to any function which exists in base class and derive class both, then it will always make a call to function of base class. If we have overidden the method in derive class then it wlll call the derive class function. 

For example… 


objB.func1(); //Calls the base class function. (In case of new keyword)

objB.func2(); //Calls the derive class function. (Override)

objB.func3(); //Calls the base class function.(Same prototype in both the class.)

Note: 
// This will throw a compile time error. (Casting is required.) 

DeriveClass objB = new BaseClass(); 


//This will throw run time error. (Unable to cast) 

DeriveClass objB = (DeriveClass) new BaseClass(); 

Object Oriented Programming Concepts (OOPS) in C#.net

c# training online Introduction to Object Oriented Programming Concepts (OOPS) in C#.net Introduction to Object Oriented Programming Concepts (OOPS) in C#.net


Class:
 It is a collection of objects. or we can say class describes , what an object is.

Object:
It is a real time entity. That is a real world existance of any substance can be called as an object. An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior. 
For example,  a Student (object) can give the name or address. In pure OOP terms an object is an instance of a class.


Class is composed of three things name, attributes, and operations

  public class student
   {
    }
student blessy=new student ();

According to the above sample we can say that Student object, named blessy , has created as an object of  student class.


Encapsulation:
Encapsulation is a process of binding the data members and member functions into a single unit.
Example for encapsulation is class. A class can contain data structures and methods.
Consider the following class

public class Triangle
{
public Triangle()
{
}
protected double height;
protected double width;


public double getarea()
{
Double area=height * width ;
if (area<0)
return 0;
return area;
}
}
In this example we encapsulate some data such as height, width and method 
getarea.  Other methods or objects can interact with this object through methods that have public access modifier

Abstraction:

Abstraction is a process of hiding the implementation details and displaying the essential features.
Example1: A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker’s works.  You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone.
So here the Laptop is an object that is designed to hide its complexity.
How to abstract: - By using Access Specifiers

.Net has five access Specifiers

Public -- Accessible outside the class through object reference.
Private -- Accessible inside the class only through member functions.
Protected -- Just like private but Accessible in derived classes also through member functions.
Internal -- Visible inside the assembly. Accessible through objects.
Protected Internal -- Visible inside the assembly through objects and in derived classes outside the assembly through member functions.

Example:-
public class Class1
    {
        int  i;                                                                //No Access specifier means private
        public  int j;                                                 // Public
        protected int k;                                         //Protected data
        internal int m;                                        // Internal means visible inside assembly
        protected internal int n;        //inside assembly as well as to derived classes outside      
                                                      //assembly
        static int x;                                          // This is also private
        public static int y;                           //Static means shared across objects
        [DllImport("MyDll.dll")]
        public static extern int MyFoo();       //extern means declared in this assembly defined in                             
                                                                     //some other assembly
        public void myFun2()
        {
            //Within a class if you create an object of same class then you can access all data members through object reference even private data too
            Class1 obj = new Class1();
            obj.i =10; //Error can’t access private data through object.But here it is accessible.:)
            obj.j =10;
            obj.k=10;
            obj.m=10;
            obj.n=10;
       //     obj.s =10;  //Errror Static data can be accessed by class names only
            Class1.x = 10;
         //   obj.y = 10; //Errror Static data can be accessed by class names only
            Class1.y = 10;
        }
    }

 [STAThread]
        static void Main()
        {
           //Access specifiers comes into picture only when you create object of class outside the class
            Class1 obj = new Class1();
       //     obj.i =10;             //Error can’t access private data through object.
            obj.j =10;
      //      obj.k=10;     //Error can’t access protected data through object.
            obj.m=10;
            obj.n=10;
       //     obj.s =10;  //Errror Static data can be accessed by class names only
            Class1.x = 10;  //Error can’t access private data outside class
         //   obj.y = 10; //Errror Static data can be accessed by class names only
            Class1.y = 10;
        }

In object-oriented software, complexity is managed by using abstraction.
Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex details.

Inheritance:

Inheritance is a process of deriving the new class from already existing class
C# is a complete object oriented programming language. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective use of inheritance, you can save lot of time in your programming and also reduce errors, which in turn will increase the quality of work and productivity. A simple example to understand inheritance in C#.

Using System;
Public class BaseClass
{
    Public BaseClass ()
    {
        Console.WriteLine ("Base Class Constructor executed");
    }
                                 
    Public void Write ()
    {
        Console.WriteLine ("Write method in Base Class executed");
    }
}
                                 
Public class ChildClass: BaseClass
{
                                 
    Public ChildClass ()
    {
        Console.WriteLine("Child Class Constructor executed");
    }
   
    Public static void Main ()
    {
        ChildClass CC = new ChildClass ();
        CC.Write ();
    }
}
  • In the Main () method in ChildClass we create an instance of childclass. Then we call the write () method. If you observe the ChildClass does not have a write() method in it. This write () method has been inherited from the parent BaseClass.
  • The output of the above program is

    Output:
      Base Class Constructor executed
      Child Class Constructor executed
      Write method in Base Class executed

    this output proves that when we create an instance of a child class, the base class constructor will automatically be called before the child class constructor. So in general Base classes are automatically instantiated before derived classes.
  • In C# the syntax for specifying BaseClass and ChildClass relationship is shown below. The base class is specified by adding a colon, ":", after the derived class identifier and then specifying the base class name.
Syntax:  class ChildClassName: BaseClass
              {
                   //Body
              }
  • C# supports single class inheritance only. What this means is, your class can inherit from only one base class at a time. In the code snippet below, class C is trying to inherit from Class A and B at the same time. This is not allowed in C#. This will lead to a compile time error: Class 'C' cannot have multiple base classes: 'A' and 'B'.
public class A
{
}
public class B
{
}
public class C : A, B
{
}
  • In C# Multi-Level inheritance is possible. Code snippet below demonstrates mlti-level inheritance. Class B is derived from Class A. Class C is derived from Class B. So class C, will have access to all members present in both Class A and Class B. As a result of multi-level inheritance Class has access to A_Method(),B_Method() and C_Method().

    Note: Classes can inherit from multiple interfaces at the same time.

Using System;
Public class A
{
    Public void A_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
}
Public class B: A
{
    Public void B_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
}
Public class C: B
{
    Public void C_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
                   
    Public static void Main ()
    {
        C C1 = new C ();
        C1.A_Method ();
        C1.B_Method ();
        C1.C_Method ();
    }
}
  • When you derive a class from a base class, the derived class will inherit all members of the base class except constructors. In the code snippet below class B will inherit both M1 and M2 from Class A, but you cannot access M2 because of the private access modifier. Class members declared with a private access modifier can be accessed only with in the class. We will talk about access modifiers in our later article.

    Are private class members inherited to the derived class?
 Yes, the private members are also inherited in the derived class but we will not be able to access them. Trying to access a private base class member in the derived class will report a compile time error.


Using System;
Public class A
{
    Public void M1 ()
    {
    }
    Private void M2 ()
    {
    }
}
         
Public class B: A
{
    Public static void Main ()
    {
        B B1 = new B ();
        B1.M1 ();
        //Error, Cannot access private member M2
        //B1.M2 ();
    }
}
Method Hiding and Inheritance We will look at an example of how to hide a method in C#. The Parent class has a write () method which is available to the child class. In the child class I have created a new write () method. So, now if I create an instance of child class and call the write () method, the child class write () method will be called. The child class is hiding the base class write () method. This is called method hiding.

If we want to call the parent class write () method, we would have to type cast the child object to Parent type and then call the write () method as shown in the code snippet below.
Using System;
Public class Parent
{
    Public void Write ()
    {
        Console.WriteLine ("Parent Class write method");
    }
}
 
Public class Child: Parent
{
    Public new void Write ()
    {
        Console.WriteLine ("Child Class write method");
    }
   
    Public static void Main ()
    {
        Child C1 = new Child ();
        C1.Write ();
        //Type caste C1 to be of type Parent and call Write () method
        ((Parent) C1).Write ();
    }
}
Polymorphism:
When a message can be processed in different ways is called polymorphism. Polymorphism means many forms.
 
Polymorphism is one of the fundamental concepts of OOP.
 
Polymorphism provides following features: 
  • It allows you to invoke methods of derived class through base class reference during runtime.
  • It has the ability for classes to provide different implementations of methods that are called through the same name.
Polymorphism is of two types: 
  1. Compile time polymorphism/Overloading
  2. Runtime polymorphism/Overriding
Compile Time Polymorphism
 
Compile time polymorphism is method and operators overloading. It is also called early binding.
 
In method overloading method performs the different task at the different input parameters.
 
Runtime Time Polymorphism
 
Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding.
 
When overriding a method, you change the behavior of the method for the derived class.  Overloading a method simply involves having another method with the same prototype.
 
Caution: Don't confused method overloading with method overriding, they are different, unrelated concepts. But they sound similar.
 
Method overloading has nothing to do with inheritance or virtual methods.
 
Following are examples of methods having different overloads:
 
void area(int side);
void area(int l, int b);
void area(float radius);
 
Practical example of Method Overloading (Compile Time Polymorphism)
 
using System;
 
namespace method_overloading
{
    class Program
    {
        public class Print
        {
           
            public void display(string name)
            {
                Console.WriteLine ("Your name is : " + name);
            }
 
            public void display(int age, float marks)
            {
                Console.WriteLine ("Your age is : " + age);
                Console.WriteLine ("Your marks are :" + marks);
            }
        }
       
        static void Main(string[] args)
        {
 
            Print obj = new Print ();
            obj.display ("Blessy");
            obj.display (34, 76.50f);
            Console.ReadLine ();
        }
    }
}
 
Note: In the code if you observe display method is called two times. Display method will work according to the number of parameters and type of parameters.

When and why to use method overloading
 
Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task.
 
You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing.
 
Method overloading showing many forms.
 
using System;
 
namespace method_overloading_polymorphism
{
    Class Program
    {
        Public class Shape
        {
            Public void Area (float r)
            {
                float a = (float)3.14 * r;
                // here we have used function overload with 1 parameter.
                Console.WriteLine ("Area of a circle: {0}",a);
            }
 
            Public void Area(float l, float b)
            {
                float x = (float)l* b;
                // here we have used function overload with 2 parameters.
                Console.WriteLine ("Area of a rectangle: {0}",x);
 
            }
 
            public void Area(float a, float b, float c)
            {
                float s = (float)(a*b*c)/2;
                // here we have used function overload with 3 parameters.
                Console.WriteLine ("Area of a circle: {0}", s);
            }
        }
 
        Static void Main (string[] args)
        {
            Shape ob = new Shape ();
            ob.Area(2.0f);
            ob.Area(20.0f,30.0f);
            ob.Area(2.0f,3.0f,4.0f);
            Console.ReadLine ();
        }
    }
}
 
Things to keep in mind while method overloading
 
If you use overload for method, there are couple of restrictions that the compiler imposes.
 
The rule is that overloads must be different in their signature, which means the name and the number and type of parameters.
 
There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name.