Tuesday 7 March 2017

Interview Questions on Inheritance

What is inheritance?

The method of constructing one class from another is called Inheritance.The derived class inherits all the properties and methods from the base class and it can add its own methods also.

Are constructors and destructors inherited ?

No.

What are Advantages of Inheritance?

a) Code re usability-Public and protected methods can be used in derived classes
b) Extensibility- base class can be extended as per business logic in derived classes.
c) Polymorphism.

What are diff types of inheritance?

a) Single inheritance --Class B is derived from base class A. A->B
b) Multiple inheritance ---Class C derives from both A and B.  A,B->C
c) Multilevel inheritance--Class B derives from Class base class A.class C derives from B.  A->B->C 
d) Hybrid inheritance --class B and C derives from same base class A.  A->B,C
.

Is multiple inheritance possible in C#.Why??

No. because
a) Its not supported by CLR since its support many diff language and not all languages can have multiple inheritance concept. 
b) Because of the complexities involved where method name can clash when two diff classes have same method name.This is resolved by pointers in C++ but its not possible in c#.

Instead interfaces can be used to achieve the same.

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

NO.

How do you prevent a class from being inherited ?

a) Make the class as sealed.
b) Add private constructors to the class.

Can derive class have public modifier when there are no modifiers specified on the base class?

No. because 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.

Does structs inherit from interfaces?

Yes structs can inherit only from interface.

What do you mean by sealed keyword ?

If you mark a class as sealed it means that you cannot inherit from it but you can create objects of that class.

Can you mark method as sealed ?

Yes.But for a method to be marked as sealed you need to have override keyword also.

What do you mean by upcasting and downcasting ?

Upcasting is an operation that creates a base class reference from a subclass reference. (subclass -> superclass) (i.e. Manager -> Employee)
downcasting is an operation that creates a subclass reference from a base class reference. (superclass -> subclass) (i.e. Employee -> Manager)

No comments:

Post a Comment