Hi
I would like to know which of the following is correct uni-directional association between class A and class B.(A->B)
1.

class A
{ 
int num; 
B obj_B; 
A(){ 
//constructor code; 
} 
} 

class B
{ 
int num; 
B(){ 
//constructor code; 
} 
}

2.

class A
{ 
int num; 
A(B obj_B){ 
//constructor code; 
} 
} 
class B
{ 
int num; 
B(){ 
//constructor code; 
} 
}

What I came to know that for uni-directional association following things should be there in a code..(correct me if it is wrong..I just started learning OOAD)

i. class A has object of class B as an attribute.
ii. class B object may be initialized in constructor of class A

Above code snippets satisfy one of the above points, which one of them to choose as uni-directional association?

They both do the same thing it doesn't matter which one to use.b Whether you pass the value of B to the A through the constructor or not it the same:

1.

B bInst = new B();
bInst.num = 10; // here we are referring to the num of B

A aInst = new A();

aInst.obj_B = bInst;
aInst.num = 5; // here we are referring to the num of A

Or
2.

B bInst = new B();
bInst.num = 10; // here we are referring to the num of B

A aInst = new A(bInst );

aInst.num = 5; // here we are referring to the num of A

They both do the same thing.
Of course you will have to make them public (obj_B, num) or declare get/set methods in the A class for the obj_B and the num

This article has been dead for over six months. Start a new discussion instead.