2

Possible Duplicate:
What is an abstract class ?

1.What is the point of creating a class that can't be instantiated?

Most commonly to serve as a base-class or interface (some languages have a separate interface construct, some don't) - it doesn't know the implementation (that is to be provided by the subclasses / implementing classes)

2.Why would anybody want such a class?

For abstraction and re-use

3.What is the situation in which abstract classes become NECESSARY?can anyone brief it with an example?

Community
  • 1
  • 1
bala3569
  • 10,832
  • 28
  • 102
  • 146

5 Answers5

6

It isn't that abstract class are always necessary, but they're often quite convenient. Suppose I want to write a parser for a particular kind of text file.

// hasty code, might be written poorly
public abstract class FileParser<T> {
    private readonly List<T> _contents;
    public IEnumerable<T> Contents {
        get { return _contents.AsReadOnly(); }
    }

    protected FileParser() {
        _contents = new List<T>();
    }

    public void ReadFile(string path) {
        if (!File.Exists(path))
            return;

        using (var reader = new StreamReader(path)) {
            while (!reader.EndOfStream) {
                T value;
                if (TryParseLine(reader.ReadLine(), out value))
                    _contents.Add(value);
            }
        }
    }

    protected abstract bool TryParseLine(string text, out T value);
}

After throwing together something like the above, I've finished with the boilerplate code any FileParser-esque class would need. All I'd need to do for any derived class is simply override the one abstract method--TryParseLine--rather than write all the same tedious stuff dealing with streams, etc. Moreover, I could easily add functionality later--such as exception handling--and it will apply to all derived classes.

Dan Tao
  • 125,917
  • 54
  • 300
  • 447
5

Abstract classes allow you to write a common piece of code that will defer specific decisions to derived classes, thus reducing code duplication.

Otávio Décio
  • 73,752
  • 17
  • 161
  • 228
  • @Otávio Décio:Necessary when the base-class can provide no meaningful default-implementation for a method?? – bala3569 Apr 26 '10 at 12:26
  • 1
    @bala3569: An abstract base class *can* provide a meaningful default implementation for a method (or for most of it). See my answer. – Dan Tao Apr 26 '10 at 12:28
5

You (may) need abstract classes when you create an inheritance tree, with a single ancestor that cannot be instantiated, simply because it is unknown how some methods could be implemented.

Marking a class as abstract is telling the compiler about:

  • Example 1
    If you need a single ancestor for a Car and a Bicycle, you would probably create a Vehicle class. You cannot initiate this Vehicle class, because it is uncompleted. A Vehicle itself will not work. That's why Vehicle will be abstract.

  • Example 2
    Another example from the .Net framework. The Stream class is an abstract class that provides basic I/O functionality. It provides a Read and Write method to handle bytes to the underlaying stream.

This stream can be a FileStream, NetworkStream, MemoryStream, and so on. The Stream itself does not know how to read or write from the concrete implementation of the stream. But some methods of Stream are implemented, because they are shared by all instances of the stream.

This is not possible to do with an interface. So you need to create a class. Since the Read and Write methods cannot be implemented, Stream is marked as abstract. This will prevent the Stream class from being created as-is.

Ken Kin
  • 4,503
  • 3
  • 38
  • 76
GvS
  • 52,015
  • 16
  • 101
  • 139
2

Abstract classes are never strictly necessary. You can always use a non-abstract class and provide stubs for methods that would otherwise be abstract. You can also approximate aspects of abstract by giving a class only protected constructors.

But non of this is the point. When a class is used to model the generalized properties and behaviour of a group of subclasses, you want to mark it abstract to make your intentions clear.

H H
  • 263,252
  • 30
  • 330
  • 514
2

I know I need to save information in between times my application is executed.

I know roughly what methods I'll need to accomplish this. I also can provide several methods which perform various parts of the overall data storage operation.

I know my customers have different requirements for data storage, based on preferences (MS Sql, Oracle) and laws (health industry security requirements).

How can I provide an object that does 80% of the heavy lifting, but leaves the last 20% open for customization?

An abstract base class allows us to customize that last 20% for each customer yet reuse the 80% of common code in the base class. Also, abstract classes don't suffer from versioning issues that interfaces face, which is a bonus.

I can code my application, provide default implementations of the abstract base class, test it and deploy it without actually having to have a different version for each client. As clients request different storage methods, a different implementation can be supplied and used at runtime via dependency injection.

Community
  • 1
  • 1