जगदीश खोलिया: OOPS frequently asked questions

Sunday, May 20, 2012

OOPS frequently asked questions

What is Virtual method?
Virtual Method has implementation & provide the derived class with the option to override it.

Can Struct be inherited?

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

What is Inheritance?

It provides a convenient way to reuse existing fully tested code in different context thereby saving lot of coding.

Inheritance of classes in C# is always implementation Inheritance.

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

What is New modifiers?

The new modifiers hides a member of the base class.

What is Abstract Class?

Abstract class is a class that can not be instantiated, it exists extensively for inheritance and it must be inherited. 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.

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.

What is an Interface?

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

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.

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 have one or more abstarct methods, ie method body only no implementation.
Interfaces: These are same as abstract classes only difference is we can only define method definition and no implementation.
When to use wot 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.

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

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.

Default Access modifiers in C#?

An enum has default modifier as public

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

An interface has default modifier as public

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

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

Can we call a base class method without creating instance?

Yep. But ..

* Its possible If its a static method.

* Its possible by inheriting from that class also.

* Its possible from derived classes using base keyword.

What is a private constructor? Where will you use it?

When you declare a Constructor with Private access modifier then it is called Private Constructor. We can use the private constructor in singleton pattern.

If you declare a Constructor as private then it doesn’t allow to create object for its derived class, i.e you loose inherent facility for that class.

Can we declare private class in a Namespace?

No. If you try to create a private class in a Namespace, Compiler will throw a compile time error “Namespace elements cannot be explicitly declared as private, protected, or protected internal”.

Reason: The message says it all. Classes can only be declared as private, protected or protected internal when declared as nested classes, other than that, it doesn't make sense to declare a class with a visibility that makes it unusable, even in the same module. Top level classes cannot be private, they are "internal" by default, and you can just make them public to make them visible from outside your DLL.

What Are Attributes in DotNet?

An Attribute is a declarative tag which can be used to provide information to the compiler about the behaviour of the C# elements such as classes and assemblies.
C# provides convenient technique that will handle tasks such as performing compile time operations , changing the behaviour of a method at runtime or maybe even handle unmanaged code.
C# Provides many Built-in Attributes

Some Popular ones are

- Obsolete
- DllImport
- Conditional
- WebMethod

and Many more.
Members please keep on posting more responses providing more In-Built attributes.

What can you do to make class available for inheritance but you need to prevent it's method to come in inheritance chain?

Well, Declare a class with public access specifier and mark all it's method to sealed . As anything which is declared with sealed keyword cannot be inherited.

What's the Difference between Interface and Abstract Class

Abstract Class:
Have constructors.
Not necessarily for the class inheriting it to Implement all the Methods.
Doesn't Support Multiple Inheritance.

Where everything is Opposite in the Interfaces.

What are the various types of Constructors


Public : Accessible to All
Private: Those classes in which only static members are there and you don't want there objects to be created in any class.
Static: Used for initializing only the static members of the class. These will be invoked for the very first time the class is being loaded on the memory. They cannot accept any arguments. Static Constructors cannot have any access modifiers.
Intern: implementations of the abstract class to the assembly defining the class. A class containing an internal constructor cannot be instantiated outside of the assembly (Namespace).
and External

What are Constructors ?

Constructors are used for initializing the members of a class whenever an object is created with the default values for initialization.

If no constructor defined then the CLR will provide an implicit constructor which is called as Default Constructor.

A class can have any number of constructors provided they vary with the number of arguments that are passed, which is they should have different signatures.

Constructors do not return a value
Constructors can be overloaded

When to Use Abstract Classes and When Interfaces.


If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.

If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.

If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.

If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

Diversities between an abstract method & virtual method ?


An Abstract method does not provide an implementation and forces overriding to the deriving class (unless the deriving class also an abstract class), where as the virtual method has an implementation and leaves an option to override it in the deriving class. Thus Virtual method has an implementation & provides the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method.

What is Early binding and late binding?


Calling a non-virtual method, decided at a compile time is known as early binding. Calling a virtual method (Pure Polymorphism), decided at a runtime is known as late binding.

Difference between ASP Session and ASP.NET Session?


Asp.net session supports cookie less session & it can span across multiple servers.

Illustrate Server.Transfer and Response.Redirect?


Server.Transfer, transfers the control of a web page, posting a form data, while Response.Redirect simply redirects a page to another page, it can not post a form data to another page. Server.Transfer is more efficient over the Response.Redirect, because Response.Redirect causes a round trip to server as the page is processed once again on the client and a request is made to server there after.
But the browser url is not changed in case of Server.Transfer i.e. Browser history is not modified in using it.

How's method overriding different from overloading?


When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.

Static datamembers should be initialized inside the constructor. True or False.


False. Static datamembers should not be initialised inside constructor.

Static methods can not use non static members. True or False.


True

Name the operators that cannot be overloaded.

sizeof
.
.*
.->
::
?:

What is "this" pointer?


This pointer is a pointer which points to the current object of a class. this is actually a keyword which is used as a pointer which differentiate the current object with global object.

Difference between sealed and static classes



sealed classes:

1)we can create their instances, but cannot inherit them

ex:

sealed class demo
{

}

class abc:demo
{
--Wrong
}
2)They can contain static as well as nonstatic members.

static classes:

1)we can neither create their instances, nor inherit them

ex:
static class Program
{

}

2)They can have static members only.

Differences between a structure and class


Structure:

1)It is a Value Type
2)Its variable directly contains the data on the stack
3)Each structure variable has its independent copy
of data.
4)One structure cannot inherit other
5)They do not have destructors
6)They do no have explicit parameterless constructors
7)we cannot put sealed /abstract modifiers before the structures.
8)Easier memory management
9)examples:
int, short,long,DateTime,
Point
(predefined)

Uses:
Structures are typically used for handling
small amounts of data or where inheritance, overriding is not required
example: int a=100;


Class

1)It is a reference Type
2)Its variable has references to the data(data is stored in the object created in the heap) .
3)Two Class variables can refer to the same object
4)One class can inherit the other(unless the class is sealed/static)
5)Classes have destructors
6)They can have explicit parameterless constructors
7)Sealed/abstract modifers can be put before classes.
8) Comparitively Difficult memory management
9)example: SqlConnection,DataView(predefined classes)

Classes are typically used where inheritance, overriding is required
or we need to create objects capable of handling large data
example: DataSet,ArrayList can handle large data.

Difference between a Class and an object


Class:

1)It is a datatype that contains the programming logic.

2)Class is visible in the source code and resides in hard disk.

3)Class is like a template or blueprint of the object. It implements reusability,

encapsulation, inheritance

example:Button is a class with properties like Text,BackColor,
events like click, methods like Focus

Object:

1)it is a chunk of memory that implements the class logic.

2)Object is in the RAM and not visible in source code.

3)It is the real world implementation of the class.
Each object has its own copy of data.
example: Button1, Button2 are the objects of Button class.

Define OOPS. What are its benefits?


OOPS

Object Oriented Programming Stuctures:

It is a programming methodology in which the programs are organized as collections of objects.Each object represents an instance of some class.The classes can be interrelated to each other through inheritance

OOPS revolves around these concepts:

1)Class
2)Object
3)Inheritance
4)Polymorphism
5)Abstraction
6)Encapsulation
-----------------------------------------------------
Advantages:
1)Code reusability: define a class and n number of objects implement the class
logic: example: Button class and n number of Button objects


2)Inheritance : Eliminates redundant code and extend the use of existing classes.

example: 1)we can create our own TextBox by inheriting from the TextBox class.
2)We can inherit one Windows Frorm into another.

3)Encapsulation: The programmer can hide the data and functions in a class from other classes.It is accomplished through modifiers like private, protected,
protected internal.


4)Easy to Maintain and Upgrade:
If we want to make changes in a class, we can make them and save the changes in the .dll This .dll can easily be updated in the client by using Update Reference.

5)Polymorphism provides us with methods extensibility.
we can have different methods with same name, but with different kinds of behavior

ex:
Console.WriteLine("welcome");
Console.WriteLine(100);


6)Abstraction allows us to define a common definition of a base class
that multiple derived classes can share.
For example,
create an abstract class bank with simple interest function
This function will be implemented in the derived classes of
the bank class.
ex: 1)icici class will have its own simple interest.
2)ABC class will have its own simple interest.

icici and ABC both are child classes of bank class.

Can we have an Abstract class without having any abstract method ??


Yes we can have Abstract class without having any abstract method ..

See the code below
using System;

abstract class A
{
public void Hello()
{
Console.WriteLine(" Say Hi");
}
}

class B:A
{
}

class Demo
{
public static void Main()
{
B b1 = new B();
b1.Hello();
}
}
// Output is Say HI


the class A is abstract class.. but it does not have any abstract methods..

Can we have Multiple Main Methods in one .cs file


Yes we can Have multiple Main methods in one .cs file.
The crux is we can have Multiple classes in one .cs file; and we can define one Main method in each class.

& while doing compliation we can spcify the compiler to choose the Main methods from the specific class .

for ef see the code below
using System;

class Test
{
    public static void Main()
    {
        Console.WriteLine("Test");
    }
}

class Demo
{
    public static void Main()
    {
        Console.WriteLine("Demo");
    }
}
We have got two class which we can save in single .cs file say Hello.cs

while doing compliation we can say
csc Hello.cs /main:Demo        --> In order to choose Main from the Demo class
and
csc Hello.cs /main:Test      --> In order to choose Main from the Test class

What is difference in between abstrct classes and interfaces ?


An interface offers an alternative to an abstract class for creating contract among classes and their client. The main difference in between abstract class and interface are given bellow
1. Abstract classes can have concrete methods while interfaces have no methods implemented.

2.Interface do not come in inheriting chain,while abstract classes come in inheritance .

No comments: