Skip to main content

Composition in java

Composition
  • Composition is the design technique to implement has-a relationship
  •  In classes use java inheritance or Object composition for code reuse.
  • Java composition is achieved by using instance variables that refers to other objects.
Java program to achieve composition
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package composition;
class compos
{
 
	int k=10;
	void test()
	{
		System.out.println("running test method");
	}
 
}
 
class demo
{
 
   double d=2.4;
 
   compos rf1=new compos();//non static object of demo1
 
   void disp()
   {
    System.out.println("running disp method");
 
   }
 
}
public class Sample1 
{
	public static void main(String[] args)
	{
 
		System.out.println("*****************************");
 
		demo obj1=new demo();
 
                //accessing property of demo1
		System.out.println("d value: "+obj1.d);
		obj1.disp();
		//accessing property of composition 
		System.out.println("k value: "+obj1.rf1.k);
                obj1.rf1.test();
		System.out.println("*****************************");
 
	}
}
 
output:
 
*****************************
d value: 2.4
running disp method
k value: 10
running test method
*****************************