Question

I am learning Object Oriented Programming, but I am confused about abstract class and concrete class. Some real world examples would be appreciated. And what are benefits of using one over another? When would one prefer abstract class and concrete class?

If answer is particular to any language than I am asking in context of Ruby

Was it helpful?

Solution

If you have an object which mustn't get instantiated you should use an abstract class. A concrete class, though, should be used if you want to instantiate this class.

Imagine you want several animal classes. But the rule is just to instantiate specific animals like a dog, cat or a mouse. But now all of those animals share some properties and methods - like a name. So you put them in a base class Animal to avoid code duplication. You can't create an instance of Animal though:

public abstract class Animal
{
    public string Name { get; set; }
    public void Sleep()
    {
        // sleep
    }
}

public class Cat : Animal
{
    public void Meow()
    {
        // meooooow
    }
}

public void DoSomething()
{
    var animal = new Animal(); // illegal operation
    var cat    = new Cat();    // works fine
}

OTHER TIPS

An abstract class is typically the base class for concrete classes. (derived, via OO inheritance) An Abstract class typically enforces an interface for the concrete classes. But an Abstract class could also implement common functionality to be used by the concrete classes via methods and attributes.

You cant ever instantiate an Abstract class, but instead can only instantiate the concrete classes, assuming they implement all of the necessary methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top