This post shows 2 sets of rather equivalent Java
source codes. One uses inheritance
that enable child classes to inherit properties and methods from their parent classes. Another set uses the Delegation Design Pattern
.
Inheritance
[wp_ad_camp_1]
With inheritance, we use the extends
keyword in Java
. The PitBull
class will have the name
property and getter/setter methods PLUS strayOrNot
and its associatd getter/setter methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Dog { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } class PitBull extends Dog{ private boolean strayOrNot; public boolean isStrayOrNot() { return strayOrNot; } public void setStrayOrNot(boolean strayOrNot) { this.strayOrNot = strayOrNot; } } |
Delegation Pattern
[wp_ad_camp_2]
Put simply, the class which other classes supposedly inherits their properties and methods from is made a reference variable
in those “child” classes. Method calls are routed accordingly to call methods on an object of that reference variable type.
For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | class Dog { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } class PitBull { private Dog dog; private boolean strayOrNot; public boolean isStrayOrNot() { return strayOrNot; } public void setStrayOrNot(boolean strayOrNot) { this.strayOrNot = strayOrNot; } public String getName() { return dog.getName(); } public void setName(String name) { this.dog.setName(name); } } |
[wp_ad_camp_3]