Last active
December 25, 2015 20:49
-
-
Save eskilandreen/7038473 to your computer and use it in GitHub Desktop.
Compositino vs Inheritence in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Djur is a thing that can be hungrig. By doing mumsa a Djur can become | |
* !hungrig. | |
*/ | |
public class Djur { | |
private boolean hungrig = true; | |
public boolean isHungrig() { | |
return this.hungrig; | |
} | |
public boolean setHungrig(boolean hungrig) { | |
this.hungrig = hungrig; | |
} | |
public void mumsa(Djur other) { | |
this.tugga(other); | |
this.smaska(other); | |
this.svalja(other); | |
this.setHungrig(false); | |
} | |
private void tugga(Djur other) { | |
... | |
} | |
private void smaska(Djur other) { | |
... | |
} | |
private void svalja(Djur other) { | |
... | |
} | |
} | |
/** | |
* Fisk by inheritence. Fisk knows how to mumsa because Fisk isa Djur. | |
*/ | |
public class Fisk1 extends Djur {} | |
/** | |
* Fisk by composition. Fisk knows how to mumsa because Fisk has access to an | |
* object that can perform the mumsa for it. | |
*/ | |
public class Fisk2 { | |
public Fisk(Djur me) { | |
this.me = me; | |
} | |
public void mumsa(Djur other) { | |
this.me.mumsa(other); | |
} | |
public boolean isHungrig() { | |
return this.me.isHungrig(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment