Interview Question.
When we will go for Abstract class?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Ken HPosted Aug 30, 2013, 10:14 PM
In general, if use the abstract modifier class indicates that it will serve as a base class.
using System;
namespace ConsoleApplication1
{
abstract class Person // Person is an abstract class.it as base class
{
public abstract void Name(); // In a derived class must implement it
public abstract void Work();
}
class Ken : Person
{
public override void Name() // Use the "override" keyword implement abstract method in the base class
{
Console.WriteLine("My name is Ken.\n");
}
public override void Work()
{
Console.WriteLine("My work is Student.\n");
}
}
class Program
{
static void Main(string[] args)
{
Ken k = new Ken();
k.Name();
k.Work();
}
}
}
An abstract class can also implement polymorphism:
using System;
namespace ConsoleApplication1
{
abstract class Employee
{
protected string _name;
protected Employee() { }
protected Employee(string name)
{
this._name = name;
}
public abstract void Work();
}
class Manager : Employee
{
public Manager(string name):base(name){}
public override void Work()
{
Console.WriteLine(_name +" in analyzing the stock market...\n");
}
}
class Engineer : Employee
{
public Engineer(string name) : base(name) { }
public override void Work()
{
Console.WriteLine(_name+" Writing code...\n");
}
}
class Program
{
static void Main(string[] args)
{
Employee[] emp = new Employee[2];
emp[0] = new Manager("James");
emp[1] = new Engineer("Ken");
Console.WriteLine("Start working");
foreach (Employee t in emp)
{
t.Work();
}
}
}
}
Sunny SharmaPosted Aug 10, 2013, 5:47 AM
Refer to this post and read it carefully, this answers your question:
http://www.headspring.com/two-reasons-to-use-abstract-classes-in-c/
Also, you may want to Google it.
"Basically, Abstract classes help you improve your code not only through what they can do, but also through what they can't. They can hold common features for many classes to inherit, without accidentally becoming objects themselves. They can also force you to write unique implementations of a common method, preventing human errors of forgetfulness. When you set up a class hierarchy, seriously consider whether you need a normal class to inherit from, or whether an abstract class will do. It may end up making the difference between a solid or buggy program."
Happy Learning :)
Cheers!