Index

OOPS DESIGN tagged Questions - Page 1

What is an Assembly in .NET?


- Assembly is unit of deployment like EXE or a DLL.

- An assembly consists of one or more files (dlls, exe’s, html files etc.), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing.

- An assembly is completely self-describing. An assembly contains metadata information, which is used by the CLR for everything from type checking an security to actually invoking the components methods. As all information is in the assembly itself, it is independent of registry. This is the basic advantage as compared to COM where the version was stored in registry.

- Multiple versions can be deployed side by side in different folders. These different versions can execute at the same time without interfering with each other. Assemblies can be private or shared. For private assembly deployment, the assembly is copied to the same directory as the client program that references it. No registration is needed, and no fancy installation program is required. When the component is removed, no registry cleanup is needed, and no uninstall program is required. Just delete it from the hard drive.

- In shared assembly deployment, an assembly is installed in the Global Assembly Cache (or GAC). The GAC contains shared assemblies that are globally accessible to all .NET applications on the machine.

What is abstraction in OOPS?


Abstraction means to show only the necessary details to the client of
the object. For example: When you switch on the lamp, it glows right?
Whereas you need not need to know the logic how the lamp glows!
Similarly, abstraction says expose only the details which are needed
with the user (client) of your object. So the client who is using your
class need not to be aware of the inner details like how you class do
the operations? Client needs to know just few details. This certainly
helps in re-usability of the code. The best thing of abstract is that
this decouples the user of the object and its implementation. So now
object is easy to understand and maintain also.

OOPS interview questions and answers





I would like to post some of the OOPS interview questions with answers, which were asked in the interview.



What is abstraction?

Abstraction means to show only the necessary details to the client
of the object. For example: When you switch on the lamp, it glows right?
Whereas you need not need to know the logic how the lamp glows!
Similarly, abstraction says expose only the details which are needed
with the user (client) of your object. So the client who is using your
class need not to be aware of the inner details like how you class do
the operations? Client needs to know just few details. This certainly
helps in re-usability of the code. The best thing of abstract is that
this decouples the user of the object and its implementation. So now
object is easy to understand and maintain also.





What is a class?

A user-defined data structure that groups properties and methods. Class doesn’t occupies memory.





What is an object?

Instance of Class is called object. An object is created in memory using keyword “new”.





What do you mean by Inheritance?

(1) The process of sub-classing a class to extend its functionality is called Inheritance.

(2) It provides idea of reusability.





Order of Constructor execution in Inheritance:

constructors are called in the order from the top to the bottom (parent to child class) in inheritance hierarchy.





Order of Destructor execution in Inheritance:

The destructors are called in the reverse order, i.e., from the
bottom to the top (child to parent class) in the inheritance hierarchy.





Facts of Inheritance:

(1) Multiple inheritance of classes is not allowed in C#.

(2) In C# you can implements more than one interface, thus multiple inheritance is achieved through interface.

(3) The Object class defined in the System namespace is implicitly
the ultimate base class of all the classes in C# (and the .NET
framework)

(4) Structures (struct) in C# does not support inheritance, it can only implement interfaces.





Polymorphism:

Polymorphism means same operation may behave differently on different classes. There are two types of polymorphism.

(1) Compile Time Polymorphism

(2) Run Time Polymorphism





Difference between Struct and Class

(1) Struct are Value type and are stored on stack, while Class are Reference type and are stored on heap.

(2) Struct “do not support” inheritance, while class supports inheritance. However struct can implements interface.

(3) Struct should be used when you want to use a small data structure, while Class is better choice for complex data structure.





What is the difference between instantiating structures with and without using the new keyword?

When a structure is instantiated using the new keyword, a
constructor (no-argument or custom, if provided) is called which
initializes the fields in the structure. When a structure is
instantiated without using the new keyword, no constructor is called.
Hence, one has to explicitly initialize all the fields of the structure
before using it when instantiated without the new keyword.





What is encapsulation in OOPS?

Wrapping up of data and function into a single unit is known as Encapsulation.





What are Properties?

Attribute of a object is called properties. Example:- A bus has color as property.

Example:

[C#]

private string t_Color;;


public string Color

{

get

{

return t_Color;

}

set

{

t_Color = value;

}

}

Bus Tata = new Car();

Tata.Color= "White";

Console.Write(Tata.Color);






What is a constructor?

(1) A constructor is a special method whose task is to initialize the object of its class.

(2) It is special because its name is the same as the class name.

(3) They do not have return types, not even void and therefore they cannot return values.

(4) They cannot be inherited, though a derived class can call the base class constructor.

(5) Constructor is invoked whenever an object of its associated class is created.

Note: There is always atleast one constructor in every class. If you
do not write a constructor, C# automatically provides one for you, this
is called default constructor. Eg: class Bus, default constructor is
Bus().

What are static Members?

(1) Static members belong to the whole class rather than to individual object

(2) Static members are accessed with the name of class rather than reference to objects.

Example:

[C#]

class Student


{

public int rollNo;

public int

design patterns used in .net framework


Adapter Pattern:

The adapter pattern, a common mechanism of bridging systems and
platforms, is implemented in a variety of ways in the .NET framework.
One of the most prevalent examples of this in .NET are Runtime Callable
Wrappers, or RCW's. RCW's, generated with the tlbimp.exe program,
provide adapters that let .NET managed code easily call into legacy COM
code via a .NET API.



Strategy pattern:

Both Array and ArrayList provide the capability to sort the objects
contained in the collection via the Sort method. Strategy Design Pattern
is used with Array and Arraylist to sort them using different strategy
without changing any client code using IComparable interface





Composite pattern in ASP.Net:

ASP.NET has lots of controls. A control may be a simple single item
like a Literal, or it could be composed of a complex collection of child
controls, like a DataGrid is. Regardless, calling the Render method on
either of these controls should still perform the same intuitive
function. Because the domain of controls is so diverse, there are
several intermediate derived classes like WebControl and BaseDataList
that serve as base classes for other controls. Though these classes
expose additional properties and methods, they still retain the child
management functions and core operations inherited from Control. In
fact, the use of the Composite pattern helps to hide their complexity,
if desired. Regardless of whether a control is a Literal or a DataGrid,
the use of Composite means you can just call Render and everything will
sort itself out.





Factory Pattern:

System.Convert: System.Convert class contains a host of static methods that work like factory design pattern.

System.Net.WebRequest: This class is used to request and
receive a response from a resource on the Internet.FTP, HTTP, and file
system requests are supported by default. To create a request, call the
Create method and pass in a URI. The Create method itself determines the
appropriate protocol for the request and returns the appropriate
subclass of WebRequest: HttpWebRequest, FtpWebRequest, or
FileWebRequest. The caller doesn't need to know the specifics of each
protocol, only how to invoke the factory and work with the WebRequest
that gets returned. If the URI changes from an HTTP address to an FTP
address, the code won't have to change at all.





Decorator Pattern:

System.IO.Stream: Any useful executable program involves
either reading input, writing output, or both. Regardless of the source
of the data being read or written, it can be treated abstractly as a
sequence of bytes. .NET uses the System.IO.Stream class to represent
this abstraction.



CryptoStream: System.Security.Cryptography.CryptoStream to
encrypt and decrypt Streams on the fly, without the rest of the
application needing to know anything more than the fact that it is a
Stream.





Template Method Pattern:

Custom controls are example of Template Method Pattern.

Design patterns implemented in .net framework


  • The Abstract Factory pattern is used in the ADO.NET 2.0 infrastructure (DbProviderFactory class)
  • The Template Method pattern is used in many parts of the framework (WinForms, WPF...)
  • The Builder pattern is also used quite often (DbConnectionStringBuilder, UriBuilder...)
  • Predefined instances (static properties) of StringComparer, Encoding, Color, etc are a variant of the Prototype pattern
  • The Proxy pattern is everywhere when you use .NET remoting
  • Events are a variant of the Observer pattern
  • The Iterator pattern is used in collections
  • The Strategy pattern is used, for instance, in cryptography classes
  • Visitor Pattern in ExpressionVisitor class (Syste.Linq.Expression namespace).
  • Adapter Pattern in System.Web.Abstractions - wrap up various Web classes (HttpRequest, HttpResponse) in a more unit testable way - i.e. HttpResponseBase.
  • Factory Method in Activator.CreateInstance which creates an instance of specified object.

C# OOPS Interview Questions and Answers


Class:
A user-defined data structure that groups properties and methods. Class doesn’t occupies memory.

Object:
Instance of Class is called object. An object is created in memory using keyword “new”.

Difference between Struct and Class
(1) Struct are Value type and are stored on stack, while Class are Reference type and are stored on heap.
(2) Struct “do not support” inheritance, while class supports inheritance. However struct can implements interface.
(3) Struct should be used when you want to use a small data structure, while Class is better choice for complex data structure.

What is the difference between instantiating structures with and without using the new keyword?
When a structure is instantiated using the new keyword, a constructor (no-argument or custom, if provided) is called which initializes the fields in the structure. When a structure is instantiated without using the new keyword, no constructor is called. Hence, one has to explicitly initialize all the fields of the structure before using it when instantiated without the new keyword.


Encapsulation:
Wrapping up of data and function into a single unit is known as Encapsulation.

Properties:
Attribute of object is called properties. Ex:- A bus has color as property.
Example:
[C#]

private string t_Color;;
public string Color
{
    get
    {
        return t_Color;
    }
    set
    {
        t_Color = value;
    }
}
Bus Tata = new Car();
Tata.Color= “White”;
Console.Write(Tata.Color);

Constructor:
(1) A constructor is a special method whose task is to initialize the object of its class.
(2) It is special because its name is the same as the class name.
(3) They do not have return types, not even void and therefore they cannot return values.
(4) They cannot be inherited, though a derived class can call the base class constructor.
(5) Constructor is invoked whenever an object of its associated class is created.
Note: There is always atleast one constructor in every class. If you do not write a constructor, C# automatically provides one for you, this is called default constructor. Eg: class Bus, default constructor is Bus().

Static Members:
(1) Static members belong to the whole class rather than to individual object
(2) Static members are accessed with the name of class rather than reference to objects.
Example:
[C#]
class Student
{
    public int rollNo;
    public int mathsMarks;
    public static int totalMathMarks;
}
class Test
{
    public static void main()
    {
        Student obj1Stud = new Student();
        obj1Stud.rollNo = 1;
        obj1Stud.mathsMarks = 40;
        Student obj2Stud = new Student();
        obj2Stud.rollNo = 2;
        obj2Stud.mathsMarks = 43;

        Student.totalMathsMarks = obj1Stud.mathsMarks + obj2Stud.mathsMarks;
    }
}

Static Method:
(1) Methods that you can call directly without first creating an instance of a class. Eg: Main() Method, Console.WriteLine()
(2) You can use static fields, methods, properties and even constructors which will be called before any instance of the class is created.
(3) As static methods may be called without any reference to object, you can not use instance members inside static methods or properties, while you may call a static member from a non-static context. The reason for being able to call static members from non-static context is that static members belong to the class and are present irrespective of the existence of even a single object.


Static Constructor:
In C# it is possible to write a static no-parameter constructor for a class. Such a class is executed once, when first object of class is created.

Destructor:
(1) A destructor is just opposite to constructor.
(2) It has same as the class name, but with prefix ~ (tilde).
(3) They do not have return types, not even void and therefore they cannot return values.
(4) It is invoked whenever an object is about to be garbage collected

Example:
[C#]
class Student
{
    //constructor
    Student()
    {
    }

    //destructor

    ~Student()
    {
        //freeing code here.
    
    }
}

What is the difference between the destructor and the Finalize() method? When does the Finalize() method get called?
Finalize() corresponds to the .Net Framework and is part of the System.Object class. Destructors are C#'s implementation of the Finalize() method. The functionality of both Finalize() and the destructor is the same, i.e., they contain code for freeing the resources when the object is about to be garbage collected. In C#, destructors are converted to the Finalize() method when the program is compiled. The Finalize() method is called by the .Net Runtime and we can not predict when it will be called. It is guaranteed to be called when there is no reference pointing to the object and the object is about to be garbage collected.

Garbage Collection:
(1) Garbage collection is the mechanism that reclaims the memory resources of an object when it is no longer referenced by a variable.
(2) .Net Runtime performs automatically performs garbage collection, however you can force the garbage collection to run at a certain point in your code by calling System.GC.Collect().
Advantage:
It prevents programming error that could otherwise occur by incorrectly deleting or failing to delete objects.

Enumeration:
(1) Enumeration improves code readability. It also helps in avoiding typing mistake.
(2) It is of value type


Boxing and Un-Boxing:
Boxing: means converting value-type to reference-type.
Example:
[C#]
int i = 20;
string s = i.ToSting();

UnBoxing: means converting reference-type to value-type.
Example:
[C#]
int i = 20;
string s = i.ToString(); //A temporary box will be created in the heap memory to store the value.
int j = Convert.ToInt32(s); //fetching the value from the temporary box (heap)

Inheritance
(1) The process of sub-classing a class to extend its functionality is called Inheritance.
(2) It provides idea of reusability.

Order of Constructor execution in Inheritance:
constructors are called in the order from the top to the bottom (parent to child class) in inheritance hierarchy.

Order of Destructor execution in Inheritance:
The destructors are called in the reverse order, i.e., from the bottom to the top (child to parent class) in the inheritance hierarchy.

Facts of Inheritance:
(1) Multiple inheritance of classes is not allowed in C#.
(2) In C# you can implements more than one interface, thus multiple inheritance is achieved through interface.
(3) The Object class defined in the System namespace is implicitly the ultimate base class of all the classes in C# (and the .NET framework)
(4

Why multiple inheritance is not supported in C#


C# is very popular and easy to code, because of its simplicity.

 

So what ever C# developers feel difficult and complicated to understand for programmers, they tried to avoid it. One such kind of property is multiple inheritance.

 

  • They avoided pointers
  • They avoided multiple inheritance.

Problem with multiple inheritance: Diamond problem.

 

Example:

  • Assume that class A is having a method fun(). class B and class C derives from class A.
  • And both the classes B and C, overrides method fun().
  • Now assume that class D inherits both class B, and C. (just Assumption)
  • Create object for class D.
  • D d = new D();
  • and try to access d.fun(); => will it call class B's fun() or class C's fun()?

This is the ambiguity existing in diamond problem.

 

It is not impossible to solve this problem, but it creates more confusion and complexities to the programmer while reading it. It causes more problem than it tries to solve.

 

Note: But any way, implemention of multiple inheritance indirectly possible by using interfaces.

Practical difference between abstract class and interface


Interfaces are rules (Rules because you must give an implementation to them and that you can't ignore or avoid, so that are imposed like rules) which works as a common understanding document among the various teams in software development.

Interfaces give the idea what is to be done but not how it will be done. So implementation completely depends on developer by following the given rules(Means given signature of methods).

Abstract classes may contain abstract declarations, concrete implementations, or both.

Abstract declarations are like rules to be followed and concrete implementations are like guidelines(You can use that as it is or you can ignore it by overriding and giving your own choice implementation to it).

Moreover which methods with same signature may change the behaviour in different context are provided as interface declarations as rules to implement accordingly in different contexts.

 

Example:

 

 

public interface LoginAuth{

   public String encryptPassword(String pass);

   public void checkDBforUser();

}

Now suppose you have 3 databases in your application. Then each and every implementation for that database needs to define the above 2 methods:

 

public class DBMySQL implements LoginAuth{

          // Needs to implement both methods

}

public class DBOracle implements LoginAuth{

          // Needs to implement both methods

}

public class DBAbc implements LoginAuth{

          // Needs to implement both methods

}

But what if encryptPassword() is not database dependent, and it's the same for each class? Then the above would not be a good approach.

 

Instead, consider this approach:

 

public abstract class LoginAuth{

   public String encryptPassword(String pass){

            // Implement the same default behavior here 

            // that is shared by all subclasses.

   }

 

   // Each subclass needs to provide their own implementation of this only:

   public abstract void checkDBforUser();

}

Now in each child class, we only need to implement one method - the method that is database dependent.

 

 

Similar Tags