Skip to content

Commit a30f396

Browse files
committed
Add composition to Other concepts along with an example in Java
1 parent c4e932b commit a30f396

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

Composition in Java.txt

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
Composition in Java is achieved by using instance variables that refer to other objects. For example, a Person class can have a Job instance variable which refers to their actual job, in this case Developer.
2+
3+
First we define Job as an interface, for polymorphism:
4+
5+
public interface Job {
6+
public String getRole();
7+
public void setRole(String role);
8+
public long getSalary();
9+
public void setSalary(long salary);
10+
}
11+
12+
Then we define the Developer Job:
13+
14+
public class DeveloperJob implements Job {
15+
private String role = "Developer";
16+
private long salary = 1000;
17+
18+
public String getRole() {
19+
return role;
20+
}
21+
public void setRole(String role) {
22+
this.role = role;
23+
}
24+
public long getSalary() {
25+
return salary;
26+
}
27+
public void setSalary(long salary) {
28+
this.salary = salary;
29+
}
30+
}
31+
32+
Finally we can use composition in the Person class:
33+
34+
public class Person {
35+
//composition - has-a relationship
36+
private Job job;
37+
38+
public Person(){
39+
this.job=new DeveloperJob();
40+
}
41+
public long getSalary() {
42+
return job.getSalary();
43+
}
44+
}
45+
46+
The composed Job could easily be replaced by some other one, and the salary will be returned polymorphically.

Other_concepts.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,5 @@ Data Abstraction - Data Abstraction is the process of providing only the essenti
33
Encapsulation - The property of wrapping up data values and functions into a single unit, such that all of them are related to each other and serve a common functionality. It is implemented in OOP through class. Thus, class forms a blueprint and wraps up various related functions and data values.
44

55
Polymorphism - The property of a function to exhibit different behaviour under different circumstances is called Polymorphism. It is usually implemented through function overloading. Suchh functions, having the same name, behave differently when different parameters are passed to it.
6+
7+
Composition - The principle that classes should achieve polymorphic behavior and code reuse by their composition (by containing instances of other classes that implement the desired functionality) rather than inheritance from a base or parent class. To favor composition over inheritance is a design principle that gives the design higher flexibility - it is better to compose what an object can do (HAS-A) than extend what it is (IS-A).

0 commit comments

Comments
 (0)