Tuesday, 22 March 2011

Abstract and sealed keyword interview questions

What is an Abstract class?

An abstract class is a special kind of class that cannot be instantiated. It normally contains one or more abstract methods
or abstract properties. It provides body to a class.

What is an Sealed class?

Sealed class is a class which cannot be inherited.

<b>Can a sealed class be used as a base class?</b>
No, sealed class cannot be used as a base class. A compile time error will be generated.

When do you absolutely have to declare a class as abstract?

a. If a class contains one or more abstract method.
b. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.

 Can we declare a class as sealed as well as abstract?

No, as it is against definition.A sealed class cannot be inherited but to use abstract class its necessary to inherit that class.

Can we declare a method as sealed?

In C# a method can't be declared as sealed. However when we override a method in a derived class,
we can declare the overridden method as sealed. By declaring it as sealed, we can avoid further overriding of this method.

using System;
class MyClass1
   public int x;
   public int y;
   public virtual void Method()
    Console.WriteLine("virtual method"); 
class MyClass : MyClass1
   public override sealed void Method() 
    Console.WriteLine("sealed method");  
class MainClass
{   public static void Main() 
      MyClass1 mC = new MyClass();
      mC.x = 110;
      mC.y = 150;
      Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);

No comments:

Post a Comment