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
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
}