Composition in java

Composition in java

  • Composition is the design technique to implement has-a relationship in classes.
  • In classes use java inheritance or Object composition for code reuse.
  • Java composition is achieved using instance variables that refers to other objects.
Java program to achieve composition

[pastacode lang=”markup” manual=”package%20composition%3B%0A%0Aclass%20compos%0A%7B%0A%09int%20k%3D10%3B%0A%09void%20test()%0A%09%7B%0A%09%09System.out.println(%22running%20test%20method%22)%3B%0A%09%7D%09%0A%7D%0Aclass%20demo%0A%7B%09%0A%20%20%20double%20d%3D2.4%3B%0A%20%20%20%0A%20%20%20compos%20rf1%3Dnew%20compos()%3B%2F%2Fnon%20static%20object%20of%20demo1%0A%20%20%20%0A%20%20%20void%20disp()%0A%20%20%20%7B%0A%20%20%20%20System.out.println(%22running%20disp%20method%22)%3B%0A%09%20%20%20%0A%20%20%20%7D%09%0A%7D%0Apublic%20class%20Sample1%20%0A%7B%0A%20%20%20public%20static%20void%20main(String%5B%5D%20args)%0A%09%7B%0A%09%0A%09%09System.out.println(%22*****************************%22)%3B%0A%09%09%0A%09%09demo%20obj1%3Dnew%20demo()%3B%0A%09%09%0A%20%20%20%20%20%20%20%20%2F%2Faccessing%20property%20of%20demo1%0A%09%09System.out.println(%22d%20value%3A%20%22%2Bobj1.d)%3B%0A%09%09obj1.disp()%3B%0A%09%09%2F%2Faccessing%20property%20of%20composition%20%0A%09%09System.out.println(%22k%20value%3A%20%22%2Bobj1.rf1.k)%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20obj1.rf1.test()%3B%0A%09%09System.out.println(%22*****************************%22)%3B%09%09%0A%09%7D%0A%7D” message=”” highlight=”Composition in java” provider=”manual”/]

output:
*****************************
d value: 2.4
running disp method
k value: 10
running test method
*****************************

Leave a Reply