Showing posts with label oops. Show all posts
Showing posts with label oops. Show all posts

Sunday, 13 January 2013

Interview Questions on oops

1. 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. Code below...

//C# Examplesealed class ClassA{    public int x;    public int y;}


No class can inherit from ClassA defined above. Instances of ClassA may be created and its members may then be accessed, but nothing like the code below is possible...

class DerivedClass : ClassA { } // Error

2. Implementation inheritance and interface inheritance?

  • When a class is derived from another class in such a way that it will inherit all its members to its corresponding derived class, then it is implementation inheritance. 
  • When a class inherits only the signatures of the functions from its corresponding base class, then it is interface inheritance.

  • 3. How to: Explicitly Implement Interface Members with Inheritance
      Explicit interface implementation also allows the programmer to implement two interfaces that have the same member names and give each interface member a separate implementation. This example displays the dimensions of a box in both metric and English units. The Box class implements two interfaces IEnglishDimensions and IMetricDimensions, which represent the different measurement systems. Both interfaces have identical member names, Length and Width

    // Declare the English units interface:
    interface IEnglishDimensions
    {
        float Length();
        float Width();
    }

    // Declare the metric units interface:
    interface IMetricDimensions
    {
        float Length();
        float Width();
    }

    // Declare the Box class that implements the two interfaces:
    // IEnglishDimensions and IMetricDimensions:
    class Box : IEnglishDimensions, IMetricDimensions
    {
        float lengthInches;
        float widthInches;

        public Box(float length, float width)
        {
            lengthInches = length;
            widthInches = width;
        }

        // Explicitly implement the members of IEnglishDimensions:
        float IEnglishDimensions.Length()
        {
            return lengthInches;
        }

        float IEnglishDimensions.Width()
        {
            return widthInches;
        }

        // Explicitly implement the members of IMetricDimensions:
        float IMetricDimensions.Length()
        {
            return lengthInches * 2.54f;
        }

        float IMetricDimensions.Width()
        {
            return widthInches * 2.54f;
        }

        static void Main()
        {
            // Declare a class instance box1:
            Box box1 = new Box(30.0f, 20.0f);

            // Declare an instance of the English units interface:
            IEnglishDimensions eDimensions = (IEnglishDimensions)box1;

            // Declare an instance of the metric units interface:
            IMetricDimensions mDimensions = (IMetricDimensions)box1;

            // Print dimensions in English units:
            System.Console.WriteLine("Length(in): {0}", eDimensions.Length());
            System.Console.WriteLine("Width (in): {0}", eDimensions.Width());

            // Print dimensions in metric units:
            System.Console.WriteLine("Length(cm): {0}", mDimensions.Length());
            System.Console.WriteLine("Width (cm): {0}", mDimensions.Width());
        }
    }



    4. Access the base class method with derived class objects

    First cast the derived class object to base class type and if you call method it invokes base class method. Keep in mind it works only when derived class method is shadowed


    public class BaseClass{    public void Method1()    {        string a = "Base method";    }}
    public class DerivedClass : BaseClass{    public new void Method1()    {        string a = "Derived Method";    }}
    public class TestApp{    public static void main()    {        DerivedClass derivedObj = new DerivedClass();        BaseClass obj2 = (BaseClass)derivedObj;        obj2.Method1();  // invokes Baseclass method
        }}


    5.Difference between ‘Shadowing’ and ‘Overriding’ (Shadowing vs Overriding) – C#


    Shadowing : Creating an entirely new method with the same signature as one in a base class.
    Overriding: Redefining an existing method on a base class.
    • Both are used when a derived class inherits from a base class
    Both redefine one or more of the base class elements in the derived class

    class A
     {
     public int M1()
     {
     return 1;
     }
     public virtual int M2()
     {
     return 1;
     }
     }
    class B : A
     {
     public new int M1()
     {
     return 2;
     }
     public override int M2()
     {
     return 2;
     }
     }
    class Program
     {
     static void Main(string[] args)
     {
     B b = new B();
     A a = (A)b;
     Console.WriteLine(a.M1()); //Base Method
     Console.WriteLine(a.M2()); //Override Method
     Console.WriteLine(b.M1());
     Console.WriteLine(b.M2());
     Console.Read();
     }
     }
    6. Shadowing vs Overriding

    It is easy to confuse shadowing with overriding. Both are used when a derived class inherits from a base class, and both redefine one declared element with another. But there are significant differences between the two.

    You normally use overriding in the following cases:
    • You are defining polymorphic derived classes.
    • You want the safety of having the compiler enforce the identical element type and calling sequence.
    You normally use shadowing in the following cases:
    • You anticipate that your base class might be modified and define an element using the same name as yours.
    • You want the freedom of changing the element type or calling sequence.


    suppose you have this classes:

    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;}
    }

    then when you call this:

    A clA = new A();
    B clB = new B();

    Console.WriteLine(clA.Foo()); // output 5
    Console.WriteLine(clA.Bar()); // output 5
    Console.WriteLine(clB.Foo()); // output 1
    Console.WriteLine(clB.Bar()); // output 1

    //now let's cast B to an A class
    Console.WriteLine(((A)clB).Foo()); // output 5 <<<--
    Console.WriteLine(((A)clB).Bar()); // output 1

    Suppose you have a base class and you use the base class in all your code instead of the inherited classes, and you use shadow, it will return the values the base class returns instead of following the ineritance tree of the real type of the object.
    7. Common c# Interfaces
    System.Configuration.IApplicationSettingsProvider System.Linq.IQueryable
    System.Configuration.IConfigurationSectionHandler System.Net.ICredentials
    System.Data.IDataAdapter System.Web.IHttpHandler
    System.Data.IDataParameter System.Web.IHttpModule
    System.Data.IDataReader System.Web.SessionState.IHttpSessionState
    System.Data.IDbCommand System.Web.SessionState.IReadOnlySessionState
    System.Data.IDbConnection System.Web.SessionState.IRequiresSessionState
    System.Data.IDbDataAdapter System.Xml.Serialization.IXmlSerializable
    System.Security.Principal.IPrincipal System.Security.Principal.IIdentity

    Monday, 19 September 2011

    OOPS Interview Question

    1. You have one base class virtual function how will call that function from derived class?
    Answer :
    class a
    {
    public virtual int m()
    {
    return 1;
    }
    }
    class b:a
    {
    public int j()
    {
    return m();
    }
    }
    2. Can we call a base class method without creating instance?
    Answer :

    Its possible If its a static method.
    Its possible by inheriting from that class also.
    Its possible from derived classes using base keyword.
    3. What is Method Overriding? How to override a function in C#?
    Answer :
    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
    4. What’s an abstract class?
    Answer :
    A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.
    5. When do you absolutely have to declare a class as abstract?
    Answer :
    1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
    2. When at least one of the methods in the class is abstract.
    6. What is an interface class?
    Answer :
    Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.
    7. What happens if you inherit multiple interfaces and they have conflicting method names?
    Answer :
    It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares it is okay.
    8. What’s the difference between an interface and abstract class?
    Answer :
    In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.
    9. How is method overriding different from method overloading?
    Answer :
    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 name within the class.
    10. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?
    Answer :
    Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.
    11. What are the different ways a method can be overloaded?
    Answer :
    Different parameter data types, different number of parameters, different order of parameters.
    12. Can you prevent your class from being inherited by another class?
    Answer :
    Yes. The keyword “sealed” will prevent the class from being inherited.
    13. What’s the C# syntax to catch any possible exception?
    Answer :
    A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}
    14. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
    Answer :
    The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element’s object, resulting in a different, yet identacle object.
    15. What’s the advantage of using System.Text.StringBuilder over System.String?
    Answer :
    StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.
    16. What’s the difference between System.String and System.Text.StringBuilder classes?
    Answer :
    System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
    17. What does the term immutable mean?
    Answer :
    The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.
    18. List out some of the exception classes in C#?
    Answer :
    Common Exception Classes :
    The following exceptions are thrown by certain C# operations.
    System.OutOfMemoryException Thrown when an attempt to allocate memory (via new) fails.
    System.StackOverflowException Thrown when the execution stack is exhausted by having too many pending method calls; typically indicative of very deep or unbounded recursion.
    System.NullReferenceException Thrown when a null reference is used in a way that causes the referenced object to be required.
    System.TypeInitializationException Thrown when a static constructor throws an exception, and no catch clauses exists to catch in.
    System.InvalidCastException Thrown when an explicit conversion from a base type or interface to a derived types fails at run time.
    System.ArrayTypeMismatchException Thrown when a store into an array fails because the actual type of the stored element is incompatible with the actual type of the array.
    System.IndexOutOfRangeException Thrown when an attempt to index an array via an index that is less than zero or outside the bounds of the array.
    System.MulticastNotSupportedException Thrown when an attempt to combine two non-null delegates fails, because the delegate type does not have a void return type.
    System.ArithmeticException A base class for exceptions that occur during arithmetic operations, such as DivideByZeroException and OverflowException.
    System.DivideByZeroException Thrown when an attempt to divide an integral value by zero occurs.
    System.OverflowException Thrown when an arithmetic operation in a checked context overflows.

    19. Can you tell me about Array Covariance?
    Answer :
    For any two reference-types A and B, if an implicit reference conversion or explicit reference conversion exists from A to B, then the same reference conversion also exists from the array type A[R] to the array type B[R], where R is any given rank-specifier (but the same for both array types). This relationship is known as array covariance. Array covariance in particular means that a value of an array type A[R] may actually be a reference to an instance of an array type B[R], provided an implicit reference conversion exists from B to A.
    Because of array covariance, assignments to elements of reference type arrays include a run-time check which ensures that the value being assigned to the array element is actually of a permitted type
    20. What are Labeled statements?
    Answer :
    A labeled-statement permits a statement to be prefixed by a label. Labeled statements are permitted blocks, but are not permitted as embedded statements.
    labeled-statement:
    identifier : statement
    A labeled statement declares a label with the name given by the identifier. The scope of a label is the block in which the label is declared, including any nested blocks. It is an error for two labels with the same name to have overlapping scopes.
    A label can be referenced from goto statements within the scope of the label. This means that goto statements can transfer control inside blocks and out of blocks, but never into blocks
    21. Do you Know about Versioning?
    Answer :
    Versioning is the process of evolving a component over time in a compatible manner. A new version of a component is source compatible with a previous version if code that depends on the previous version can, when recompiled, work with the new version. In contrast, a new version of a component is binary compatible if a program that depended on the old version can, without recompilation, work with the new version.Most languages do not support binary compatibility at all, and many do little to facilitate source compatibility. In fact, some languages contain flaws that make it impossible, in general, to evolve a class over time without breaking at least some client code.
    22. What are Deligates ?
    Answer :
    Delegates enable scenarios that C++ and some other languages have addressed with function pointers. Unlike function pointers, delegates are object-oriented, type-safe, and secure.
    Delegates are reference types that derive from a common base class: System.Delegate. A delegate instance encapsulates a method—a callable entity. For instance methods, a callable entity consists of an instance and a method on the instance. For static methods, a callable entity consists of a class and a static method on the class.
    An interesting and useful property of a delegate is that it does not know or care about the type of the object that it references. Any object will do; all that matters is that the method’s signature matches the delegate’s. This makes delegates perfectly suited for “anonymous” invocation. This is a powerful capability.
    There are three steps in defining and using delegates: declaration, instantiation, and invocation. Delegates are declared using delegate declaration syntax.
    delegate void SimpleDelegate();
    declares a delegate named SimpleDelegate that takes no arguments and returns void.