Can somebody explain to me the main differences between the principles of encapsulation and abstraction in objected-oriented programming (if possible with examples).
Sample:
// NO ABSTRACTION, NO ENCAPSULATION
const int catLegs = 4;
const int spiderLegs = 8;
Leg[] catLegs;
Leg[] spiderLegs;
void MakeCatRun(Distance b) { for (int i=0; i<catLegs; ++i) catLegs[i] += b; }
void MakeSpiderRun(Distance b) { for (int i=0; i<spiderLegs; ++i) spiderLegs[i] += b; }
Encapsulation:
// ENCAPSULATION
class Cat
{
Leg[] legs;
int nLegs;
public void Run(Distance b) { for (int i=0; i < nLegs; ++i) leg[i] += b; }
}
class Spider
{
Leg[] legs;
int nLegs;
public void Run(Distance b) { for (int i=0; i < nLegs; ++i) leg[i] += b; }
}
Abstraction:
// ABSTRACTION
class LivingBeing
{
Leg[] legs;
int nLegs;
public void Run(Distance b) { for (int i=0; i < nLegs; ++i) leg[i] += b; }
}
class Cat: LivingBeing { }
class Spider: LivingBeing { }