OOP Interview Q & A


What is OOP?

OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods.
Object-oriented programming has several advantages over procedural programming:
  • OOP is faster and easier to execute
  • OOP provides a clear structure for the programs
  • OOP helps to keep the C# code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should extract out the codes that are common for the application, and place them at a single place and reuse them instead of repeating it.


What are Classes and Objects?

Classes and objects are the two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and objects:

Another example:



  • So, a class is a template for objects, and an object is an instance of a class.
  • When the individual objects are created, they inherit all the variables and methods from the class.
  • Everything in C# is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.
  • A Class is like an object constructor, or a "blueprint" for creating objects.



Different ways to create an Object in C#?

1) Using the ‘new’ operator: A class is a reference type and at the run time, any object of the reference type is assigned a null value unless it is declared using the new operator. The new operator assigns space in the memory to the object only during run time which means the allocation is dynamic.
Syntax:
// The className() is a call
// to the constructor
className ObjectName = new className(); 
Note: The constructor can be a default constructor or a user-defined one.

2) Creating Reference to Existing Object: The reference can be declared only with the class name and reference name. The reference cannot exist independently. It has to be assigned to an already existing object of the same class. Any changes made in the reference will be saved to the object it is referring to. It is kind of like an alias.
Syntax:
className RefName;
RefName = objectName;
Example:
// C# Program to show the use of references
    using System;
    namespace Reference
    {
        class Triangle
        {
            public int side, altitude;
            // Not defining a constructor

            // Method to calculate area of the Triangle
            public double Area()
            {
                return (double)0.5 * side * altitude;
            }
        }

        class Program
        {
            static void Main(string[] args)
            {
                // Creating an object using new
                // calls the default constructor
                Triangle tri1 = new Triangle();

                // Only creates a reference of type Triangle
                Triangle tri2;

                // Displaying area of tri1
                Console.WriteLine("Area of tri1 is " + tri1.Area());

                // Assigns the reference to tri1
                tri2 = tri1;

                // Making changes in tri2
                tri2.side = 5;
                tri2.altitude = 7;

                // Displaying area of tri1
                // Changes made in the reference tri2 are reflected in tri1 also
                Console.WriteLine("Area of tri1 is " + tri1.Area());
            }
        }

    }

Output:
Area of tri1 is 0
Area of tri1 is 17.5
3) Creating an Array of objects: If you need the multiple numbers of objects of the same class you can create an array of objects. This will require you to declare the array first and then initialize each element { object in this case }. You can use for loop for initialization.
Syntax:
className[] arrayName = new className[size];
Example:
// C# Program to illustrate how to create the array of objects
    using System;
    namespace ArrayofObjects
    {
        class Circle
        {
            public int radius;

            // Definig Constructor
            public Circle()
            {
                radius = 0;
            }

            // Method to set value of radius
            public void setValue(int r)
            {
                radius = r;
            }

            // Method to calculate the area of the Circle
            public double Area()
            {
                return (double)3.14 * radius * radius;
            }
        }

        class Program
        {
            static void Main(string[] args)
            {
                // To declare an array of two objects
                Circle[] circleArray = new Circle[2];

                // Initialize the objects
                circleArray[0] = new Circle();
                circleArray[1] = new Circle();

                // to set values for the radius
                circleArray[0].setValue(1);
                circleArray[1].setValue(2);

                // for loop to display areas
                for (int i = 0; i < circleArray.Length; i++)
                {
                    Console.Write("Area of circle with radius " + (i + 1));
                    Console.Write(" is " + circleArray[i].Area() + "\n");
                }
            }
        }
    }
Output:
Area of circle with radius 1 is 3.14
Area of circle with radius 2 is 12.56




How to prevent a class from being instantiated?

There are a few ways prevent instantiation of a class:
  1. Abstract
  2. Static Class
  3. Private and protected constructor
1. Abstract
We declare a class as abstract to prevent us from creating an object of the class such as in the following example:



2. Static Class

If you try to create an instance of a static class then it also prompts you with an error after implementation of the code as in the following:


3. Private or protected constructor

If we declare a private or protected constructor then it also prevents us from creating an instance of the class as the following code shows:






Abstraction

  • Data abstraction is the process of hiding certain details and showing only essential information to the user.
  • Abstraction is needed when we need to only inherit from a certain class, but do not need to instantiate objects of that class.
  • Abstraction can be achieved with either abstract classes or interfaces.
Example: Consider a real-life scenario of withdrawing money from ATM. The user only knows that in ATM machine first enter ATM card, then enter the pin code of ATM card, and then enter the amount which he/she wants to withdraw and at last, he/she gets their money. The user does not know about the inner mechanism of the ATM or the implementation of withdrawing money etc. The user just simply know how to operate the ATM machine, this is called abstraction.

Abstract Classes and Methods

  • An abstract class is declared with the help of abstract keyword.
  • In C#, you are not allowed to create objects of the abstract class. Or in other words, you cannot use the abstract class directly with the new operator.
  • But you can create a reference by the concept of inheritance "a base class reference can point to a derived class object".
  • Example: AbstractClass object = new DerivedClass();
  • Class that contains the abstract keyword with some of its methods(not all abstract method) is known as an Abstract Base Class.
  • Class that contains the abstract keyword with all of its methods is known as Pure Abstract Base Class.
  • You are only allowed to declare the abstract methods(not define) inside the abstract class.
  • The abstract class may contain definition for non - abstract methods.
  • The class which inherit the abstract class must provide definition for all the abstract methods. If so than have to use override keyword in derived class method.
  • You are not allowed to declare the abstract methods outside the abstract class.
  • You are not allowed to declare abstract class as Sealed Class.
Example:

abstract class Demo
    {
        public abstract void Print();
        public abstract void Sample();
        public void Laptop()
        {
            Console.WriteLine("Laptop Method");
        }
    }

    class Program : Demo
    {
        public override void Print()
        {
            Console.WriteLine("Print Method");
        }

        public override void Sample()
        {
            Console.WriteLine("Sample Method");
        }

        static void Main(string[] args)
        {
            //Program p = new Program();
            Demo d = new Program();
            Test t = new Test();
            t.Print();
            t.Sample();
            d.Print();
            d.Sample();
            d.Laptop();
            Console.ReadKey();
        }
    }

    class Test : Demo
    {
        public override void Print()
        {
            Console.WriteLine("Print Method From Test");
        }

        public override void Sample()
        {
            Console.WriteLine("Sample Method From Test");
        }

    }

Output:


Advantages of Abstraction
  • It reduces the complexity of viewing the things.
  • Avoids code duplication and increases reusability.
  • Helps to increase security of an application or program as only important details are provided to the user.

Questions?

Can abstract class have constructor in C# ? If yes, why do we use constructor in abstract class? 
OR
If we cannot instantiate (construct object using new) an abstract class, then what for an constructor is in an abstract class or why should we use a constructor in abstract class?

Answer:
  • Yes, an abstract class can have a constructor, even though abstract class cannot be instantiated.
  • When we create an object of a derived class then constructor of abstract base class is implicitly called, even though we cannot instantiate an abstract class.
  • For example in below program, if we create object of derived class then abstract base class constructor will also be called.

    abstract class A
    {
        protected A()
        {
            Console.WriteLine("Abstract class constructor");
        }
    }
    //Derived class
    class B : A
    {
        public B()
        {
            Console.WriteLine("Derived class constructor");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            B obj = new B();
        }

    }

Output:




Inheritance

  • Inheritance is an important pillar of OOP(Object Oriented Programming).
  • Inheritance is the mechanism by which a class can acquire the properties of another class.
  • It is also used to reuse the code.
In C#, it is possible to inherit fields and methods from one class to another. We group the "inheritance concept" into two categories:
  • Derived Class (child) - the class that inherits from another class
  • Base Class (parent) - the class being inherited from
To inherit from a class, use the : symbol.
Important terminology:
  • Super Class: The class whose features are inherited is known as super class(or a base class or a parent class).
  • Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
  • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
C# supports 3 types of inheritance, they are:
  • Single Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Multiple inheritance is not supported by C# directly, support by Interface.
Syntax:
class derived-class : base-class  
{  
   // methods and fields  
   .
   .
}  
Example:
1. Single Inheritance: In single inheritance, subclasses inherit the features of one superclass. In image below, the class A serves as a base class for the derived class B.
2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C.
3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In below image, class A serves as a base class for the derived class B, C, and D.

Questions?

Are constructors and destructors inherited ?
No

Is circular inheritance possible. like A:B ,B:A ?
No

Can derive class have public modifier when there are no modifiers specified on the base class?
No. bc derived class cannot be more accessible that base class.

why c# does not support inheritance by structure?
Because structures are mainly used for light weight process. And if they are allowed to be inherited then they have to act as base class which is not possible as they are value types.



Diamond Problem
The Diamond problem occurs in inheritance-oriented languages that support multiple inheritance.
In this case it is possible to inherit from the same class through multiple inheritance paths, as shown in the figure below.
The question now is whether class C should have one SuperClass object, or two; i.e., should classes A and B share one SuperClass object, or should they each have their own one? Furthermore, which SuperClass’s methods should be inherited — the ones on the SuperClass instance of A, or the ones on the SuperClass instance of B?
Answer: 
  • Let’s assume that multiple inheritance was supported in .NET. In that case, we could have a class hierarchy like above image.
  • Let’s say SuperClass is an abstract class declaring some method and ClassA, ClassB are concrete classes.
  • So class C will be multiple inherited by class A and class B like:

    class SuperClass
    {
        public void Fun()
        {
            Console.WriteLine("From SuperClass");
        }
    }
    class A : SuperClass
    {
        public void Fun()
        {
            Console.WriteLine("From A");
        }
    }
    class B : SuperClass
    {
        public void Fun()
        {
            Console.WriteLine("From B");
        }
    }
    class C : A, B    //error: Multiple class inheritance not possible
    {
        static void Main(string[] args)
        {
            C p = new Program();
            p.Fun();
        }

    }

  • From the code, we see that: On calling the method Fun() using C object will cause complications such as whether to call class A’s Fun() or B’s Fun() method.
  • Therefore, in order to avoid such complications, .NET does not support multiple inheritance of classes.
  • The above complexity is known as diamond problem.


Interface

  • Another way to achieve abstraction in C#, is with interfaces.
  • An interface is a completely "abstract class", which can only contain abstract methods and properties (with empty bodies):

Example:

    interface ICustomer
    {
        void Print();
    }
  • Interface methods do not have a body - the body is provided by the "implement" class.
  • On implementation of an interface, you must override all of its methods.
  • Signature in methods in interface and implemented class must be same otherwise compiler will raise an error.
  • Interfaces can contain properties and methods, but not fields/variables.
  • Interface members are by default abstract and public. We cannot even use public explicitly.
  • An interface cannot contain a constructor (as it cannot be used to create objects).
  • An interface can inherit another interface.
  • A class inherits the interface has to provide implementation for all the interface chain.
  • Interface cannot be instantiated but as per inheritance concept "a base class reference can point to a derive class object" we can create reference like:
Interface object = new Class();

Example:

    interface ICustomer
    {
        void Print();
    }

    interface I2 : ICustomer
    {
        void I2Method();
    }

    interface I3 : I2
    {
        void Set();
    }

    class Customer : I3
    {
        public void Print()
        {
            Console.WriteLine("Print Method");
        }
        public void I2Method()
        {
            Console.WriteLine("I2Method");
        }
        public void Set()
        {
            Console.WriteLine("Set Method");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            I3 cust = new Customer();
            cust.Print();
            cust.I2Method();
            cust.Set();
        }
    }

Output:

Explicit Interface Implementation

Scenario:
A class inherits from two interfaces and both the interfaces have same method name. How should the class implement the method for both the interfaces?

Case:
    interface I1
    {
        void InterfaceMethod();
    }
    interface I2
    {
        void InterfaceMethod();
    }
    class Program : I1, I2
    {
        public void InterfaceMethod()
        {
            Console.WriteLine("Interface Method");
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            p.InterfaceMethod();
        }

    }

Now which interface method is implemented in our class: I1 or I2? So here is an ambiguity. So if we call the method which method will be called? To solve like this situation, we have to use Explicit Interface Implementation.

Solution:

Note:
  • When a class is explicitly implements an interface member, the interface member can no longer be accessed thru the reference variable, but only thru the interface variable.
  • Access modifiers are not allowed on explicitly implemented interface member.
  • Use InterfaceName.MethodName while implementation.
Here we have two ways to solve the problem:

First Way: try to TypeCast(not recomended)
  • Here if we try to call the interface method since we have only one implementation, then only one implemented interface method will call.
  • So this is a problem. To solve always use second way below.
    interface I1
    {
        void InterfaceMethod();
    }
    interface I2
    {
        void InterfaceMethod();
    }
    class Program : I1 , I2
    {
        public void InterfaceMethod()
        {
            Console.WriteLine("Interface Method");
        }

        static void Main(string[] args)
        {
            //Program p = new Program();
            //p.InterfaceMethod();

            Program p = new Program();
            ((I1)p).InterfaceMethod();
            ((I2)p).InterfaceMethod();
        }
    }

Output:

Second Way: InterfaceName.MethodName

    interface I1
    {
        void InterfaceMethod();
    }
    interface I2
    {
        void InterfaceMethod();
    }
    class Program : I1, I2
    {
        //public void InterfaceMethod()
        //{
        //    Console.WriteLine("Interface Method");
        //}

        void I1.InterfaceMethod()
        {
            Console.WriteLine("I1 InterfaceMethod");
        }
        void I2.InterfaceMethod()
        {
            Console.WriteLine("I2 InterfaceMethod");
        }
        static void Main(string[] args)
        {
            //Program p = new Program();
            //p.InterfaceMethod();

            I1 i1 = new Program();
            I2 i2 = new Program();
            i1.InterfaceMethod();
            i2.InterfaceMethod();
        }
    }

Output:

Default Implementation

Scenario:
If we want to make one of the interface method the default, then implement that method normally and the other method explicitly?

Note:

  • This makes the default method to be accessible thru class instance.

Solution:


    interface I1
    {
        void InterfaceMethod();
    }
    interface I2
    {
        void InterfaceMethod();
    }
    class Program : I1, I2
    {
        //Normal implementation
       public void InterfaceMethod()
        {
            Console.WriteLine("I1 InterfaceMethod-Default");
        }

        //Explicit implementation
       void I2.InterfaceMethod()
        {
            Console.WriteLine("I2 InterfaceMethod");
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            p.InterfaceMethod();//default call
            ((I2)p).InterfaceMethod();
        }

    }

Output:

Questions?

1.What is an Interface ?
Interface is a contract which guarantees  client(consumer) how your classes or structs are going to behave.They consists only method skeleton and no implementations.
example-
Interface i1
{
    void Method1();
}

2.Whats the naming convention of interface ?
     The interface name should start with an I.Example--IDisposable,IEnumerable  
 
3.Whats the use of Interface?
->Interface  can be used when you cannot inherit from a class like for structs.
->More than one interface can be inherited thus supporting multiple inheritance in .Net
->Interface helps in defining a common functionality across multiple types.
->Used in plug-n-play architecture. 

4.Why Interface methods cannot have access modifiers ? 
Interface methods are always public by default.

5.Can Interface have properties in them ?
 yes.a property in interface is defined as below
Interface I1
{
   int prop
   {
      get;
      set;
    }
}
get and set cannot have any body.

6.Can interface have fields ?
 No

7.Can you create instance of an interface?
No you cannot create an instance of interface.

8.Why public modifier not used in explicit implementation? 
The methods which are explicitly implemented are tied to a interface. and it can be 
accessed  only through interface reference.

9.Does structure support Inheriting from an interface ?
Yes


10.When a class A inherits from an interface I1 and another class B what should  be taken care of ?

      The class being inherited should be the base class
     example- This is how it should  be inherited

            Class A:Class B,I1

            {

            }


       This is wrong

           Class A:I1,Class B

           {

           }


11.Can a method derived from interface marked as virtual ? 
Yes and they can then be overridden

12.Why cannot you have static method in Interface? 
Because Interface methods have implementation and also can be overriden . Thera is no point in having  static methods as they should have a body and cannot be overriden.

13.Can Interface inherit another interface ?
 Yes

14.Can Interface inherit another class ?
 
Interface cannot inherit another class.

15.Can Interface have access modifier ? 

 Yes.



Encapsulation

Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield.
  • Technically in encapsulation, the variables or data of a class are hidden from any other class and can be accessed only through any member function of own class in which they are declared.
  • As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
  • Encapsulation can be achieved by: Declaring all the variables in the class as private and using C# Properties in the class to set and get the values of variables.
Example:
//C# program to illustrate encapsulation
using System;
public class DemoEncap {
      
    // private variables declared
    // these can only be accessed by
    // public methods of class
    private String studentName;
    private int studentAge;
      
    // using accessors to get and 
    // set the value of studentName
    public String Name
    {
        get
        {
            return studentName;    
        }
        set 
        {
            studentName = value;
        }
    }
      
    // using accessors to get and 
    // set the value of studentAge
    public int Age
    {
        get 
        {
            return studentAge;    
        }
        set 
        {
            studentAge = value;
        }
    }
}
  
// Driver Class
class GFG {
    static public void Main()
    {
        // creating object
        DemoEncap obj = new DemoEncap();
  
        // calls set accessor of the property Name, 
        // and pass "Ankita" as value of the 
        // standard field 'value'
        obj.Name = "Ankita";
          
        // calls set accessor of the property Age, 
        // and pass "21" as value of the 
        // standard field 'value'
        obj.Age = 21;
  
        // Displaying values of the variables
        Console.WriteLine("Name: " + obj.Name);
        Console.WriteLine("Age: " + obj.Age);
    }
}

Output:
Name: Ankita
Age: 21
Explanation: In the above program the class DemoEncap is encapsulated as the variables are declared as private. To access these private variables we are using the Name and Age accessors which contains the get and set method to retrieve and set the values of private fields. Accessors are defined as public so that they can access in other class.
Advantages of Encapsulation:
  • Data Hiding: The user will have no idea about the inner implementation of the class. It will not be visible to the user that how the class is stored values in the variables. He only knows that we are passing the values to accessors and variables are getting initialized to that value.
  • Increased Flexibility: We can make the variables of the class as read-only or write-only depending on our requirement. If we wish to make the variables as read-only then we have to only use Get Accessor in the code. If we wish to make the variables as write-only then we have to only use Set Accessor.
  • Reusability: Encapsulation also improves the re-usability and easy to change with new requirements.
  • Testing code is easy: Encapsulated code is easy to test for unit testing.

Questions?

What is Encapsulation?

  1. Encapsulation is a process of hiding the members from outside of class and implemented using access specifiers
  2. Encapsulation is also called as information hiding.
  3. Encapsulation provides a way to preserve the integrity of state data. Rather than defining public fields, private data fields should be defined.
  4. Well-encapsulated class should hide its data and the details of how it operates on data from the outside world. This is termed black box programming.
  5. Using this, implementation of the method can be changed by the class author without breaking any existing code making use of it.
An access specifier defines the scope and visibility of a class member. C# supports the following access specifiers:
  • Public
  • Private
  • Protected
  • Internal
  • Protected internal
Access Specifiers:

Access Specifiers
Accessibility
Private
Only within the containing class
Public
Anywhere, No restriction
Protected
Within the containing types and the types derived from the containing type
Internal
Anywhere within the containing assembly
Protected Internal
Anywhere within the containing assembly and from within a derived class in any other assembly




Polymorphism


Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.

Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.

Static Polymorphism

The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. They are −
  • Function overloading
  • Operator overloading
We discuss operator overloading later.

Function Overloading

You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type.
The following example shows using function print() to print different data types −
Example:

class Printdata {
      void print(int i) {
         Console.WriteLine("Printing int: {0}", i );
      }
      void print(double f) {
         Console.WriteLine("Printing float: {0}" , f);
      }
      void print(string s) {
         Console.WriteLine("Printing string: {0}", s);
      }
      static void Main(string[] args) {
         Printdata p = new Printdata();
         
         // Call print to print integer
         p.print(5);
         
         // Call print to print float
         p.print(500.263);
         
         // Call print to print string
         p.print("Hello C++");
         Console.ReadKey();
      }
   }

When the above code is compiled and executed, it produces the following result −
Printing int: 5
Printing float: 500.263
Printing string: Hello C++

Dynamic Polymorphism

C# allows you to create abstract classes that are used to provide partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality.
Here are the rules about abstract classes −
  • You cannot create an instance of an abstract class
  • You cannot declare an abstract method outside an abstract class
  • When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
The following program demonstrates an abstract class −
Example:

abstract class Shape {
      public abstract int area();
   }
   
   class Rectangle:  Shape {
      private int length;
      private int width;
      
      public Rectangle( int a = 0, int b = 0) {
         length = a;
         width = b;
      }
      public override int area () { 
         Console.WriteLine("Rectangle class area :");
         return (width * length); 
      }
   }
   class RectangleTester {
      static void Main(string[] args) {
         Rectangle r = new Rectangle(10, 7);
         double a = r.area();
         Console.WriteLine("Area: {0}",a);
         Console.ReadKey();
      }
   }

When the above code is compiled and executed, it produces the following result −
Rectangle class area :
Area: 70

When you have a function defined in a base class that you want to be implemented in an inherited class(es), you use virtual keyword in functions within the base class. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime. For this you need to use override keyword in derive class functions to override base class functions.
Dynamic polymorphism is implemented by abstract classes and virtual functions.
The following program demonstrates this −
Example:

class Shape {
      protected int width, height;
      
      public Shape( int a = 0, int b = 0) {
         width = a;
         height = b;
      }
      public virtual int area() {
         Console.WriteLine("Parent class area :");
         return 0;
      }
   }
   class Rectangle: Shape {
      public Rectangle( int a = 0, int b = 0): base(a, b) {

      }
      public override int area () {
         Console.WriteLine("Rectangle class area :");
         return (width * height); 
      }
   }
   class Triangle: Shape {
      public Triangle(int a = 0, int b = 0): base(a, b) {
      }
      public override int area() {
         Console.WriteLine("Triangle class area :");
         return (width * height / 2); 
      }
   }
   class Caller {
      public void CallArea(Shape sh) {
         int a;
         a = sh.area();
         Console.WriteLine("Area: {0}", a);
      }
   }  
   class Tester {
      static void Main(string[] args) {
         Caller c = new Caller();
         Rectangle r = new Rectangle(10, 7);
         Triangle t = new Triangle(10, 5);
         
         c.CallArea(r);
         c.CallArea(t);
         Console.ReadKey();
      }
   }

When the above code is compiled and executed, it produces the following result −
Rectangle class area:
Area: 70
Triangle class area:
Area: 25

Questions?

Explain polymorphism in C# with a simple example? 
Polymorphism allows you to invoke derived class methods through a base class reference during run-time

When can a derived class override a base class member? 
A derived class can override a base class member only if the base class member is declared as virtual or abstract.

What is the difference between a virtual method and an abstract method? 
A virtual method must have a body where as an abstract method should not have a body.

Can fields inside a class be virtual?No, Fields inside a class cannot be virtua. Only methods, properties, events and indexers can be virtual.

Give an example to show for hiding base class methods? 
Use the new keyword to hide a base class method in the derived class as shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}

public static void Main()
{
DerivedClass DC = new DerivedClass();
DC.Method();
}
}

Can you access a hidden base class method in the derived class? 
Yes, Hidden base class methods can be accessed from the derived class by casting the instance of the derived class to an instance of the base class as shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}

public static void Main()
{
DerivedClass DC = new DerivedClass();
((BaseClass)DC).Method();
}
}



Comparison

ABSTRACT CLASSINTERFACE
It contains both declaration and definition part.It contains only a declaration part.
Multiple inheritance is not achieved by abstract class.Multiple inheritance is achieved by interface.
It contain constructor.It does not contain constructor.
It can contain static members.It does not contain static members.
It can contain different types of access modifiers like public, private, protected etc.It only contains public access modifier because everything in the interface is public.
The performance of an abstract class is fast.The performance of interface is slow because it requires time to search actual method in the corresponding class.
It is used to implement the core identity of class.It is used to implement peripheral abilities of class.
A class can only use one abstract class.A class can use multiple interface.
If many implementations are of the same kind and use common behavior, then it is superior to use abstract class.If many implementations only share methods, then it is superior to use Interface.
Abstract class can contain methods, fields, constants, etc.Interface can only contain methods .
It can be fully, partially or not implemented.It should be fully implemented.

CLASSSTRUCTURE
Classes are of reference types.Structs are of value types.
All the reference types are allocated on heap memory.All the value types are allocated on stack memory.
Allocation of large reference type is cheaper than allocation of large value type.Allocation and de-allocation is cheaper in value type as compare to reference type.
Class has limitless features.Struct has limited features.
Class is generally used in large programs.Struct are used in small programs.
Classes can contain constructor or destructor.Structure does not contain constructor or destructor.
Classes used new keyword for creating instances.Struct can create an instance, without new keyword.
A Class can inherit from another class.A Struct is not allowed to inherit from another struct or class.
The data member of a class can be protected.The data member of struct can’t be protected.
Function member of the class can be virtual or abstract.Function member of the struct cannot be virtual or abstract.
Two variable of class can contain the reference of the same object and any operation on one variable can affect another variable.Each variable in struct contains its own copy of data(except in ref and out parameter variable) and any operation on one variable can not effect another variable.
Class Vs Interface
  • A Class has both definition and an implementation whereas Interface only has a definition.
  • A Class can be instantiated but an Interface cannot be instantiated You can create an instance of an Object that implements the Interface.
  • A Class is a full body entity with members, methods along with there definition and implementation. An Interface is just a set of definition that you must implement in your Class inheriting that Interface.

Encapsulation vs Data Abstraction
  • Encapsulation is data hiding(information hiding) while Abstraction is detail hiding(implementation hiding).
  • While encapsulation groups together data and methods that act upon the data, data abstraction deals with exposing to the user and hiding the details of implementation.


Comments