public abstract class Draw {
public abstract void drawShape(); // this is abstraction. Implementation detail need not to be known.
// so we are providing only necessary detail by giving drawShape(); No implementation. Subclass will give detail.
private int type; // this variable cannot be set outside of the class. Because it is private.
// Binding private instance variable with public setter/getter method is encapsulation
public int getType() {
return type;
}
public void setType(int type) { // this is encapsulation. Protecting any value to be set.
if (type >= 0 && type <= 3) {
this.type = type;
} else {
System.out.println("We have four types only. Enter value between 0 to 4");
try {
throw new MyInvalidValueSetException();
} catch (MyInvalidValueSetException e) {
e.printStackTrace();
}
}
}
}
//abstraction - exposing only the relevant behavior
public interface IMakeFire
{
void LightFire();
}
//encapsulation - hiding things that the rest of the world doesn't need to see
public class Caveman: IMakeFire
{
//exposed information
public string Name {get;set;}
// exposed but unchangeable information
public byte Age {get; private set;}
//internal i.e hidden object detail. This can be changed freely, the outside world
// doesn't know about it
private bool CanMakeFire()
{
return Age >7;
}
//implementation of a relevant feature
public void LightFire()
{
if (!CanMakeFire())
{
throw new UnableToLightFireException("Too young");
}
GatherWood();
GetFireStone();
//light the fire
}
private GatherWood() {};
private GetFireStone();
}
public class PersonWithMatch:IMakeFire
{
//implementation
}
//this method (and class) isn't coupled to a Caveman or a PersonWithMatch
// it can work with ANY object implementing IMakeFire
public void FireStarter(IMakeFire starter)
{
starter.LightFire();
}