Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why abstract classes necessary? [duplicate]

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?

like image 758
bala3569 Avatar asked Feb 18 '26 06:02

bala3569


1 Answers

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.

like image 132
Dan Tao Avatar answered Feb 19 '26 19:02

Dan Tao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!