Osama Adel
Osama Adel

Reputation: 238

How can I use composition of the classes if they have common fields in java?

How can I use composition of the classes if they have common fields and I want them to be equal?

for ex, I have 3 classes :

class SwimmingMonster, FlyingMonster and SwimmAndFlyMonster which compose FlyingMonster and SwimmingMonster . both classes has field location. and I want it to be the same in both objects objOfFly and objOfSwim in SwimAndFly class.

class SwimmingMonster{
private int[] location=new int[2];
{location[0]=0;
location[1]=0;}
void swim(int x,int y){
location[0]+=x;
location[1]+=y;}

}


class FlyingMonster{
private int[] location=new int[2];
{location[0]=0;
location[1]=0;}
void fly(int x,int y){
location[0]+=x;
location[1]+=y;}

}
class SwimAndFlyMonster{
private FlyingMonster objOfFly=new FlyingMonster();
private SwimmingMonster objOfSwim=new SwimmingMonster();
void fly(int x,int y){
objOfFly.fly(x,y);
}
void swim(int x,int y){
objOfSwim.swim(x,y);
}

}

but the problem here is that I want the field location in objOfSwim and objOfFly be equals.

so how can I do that?

is the only solution is to create a setter and getter for location in each class and do this ↓ ?

    void fly(int x,int y){
    objOfFly.fly(x,y);
    objOfSwim.set(objOfFly.get(location));
    }
    void swim(int x,int y){
    objOfSwim.swim(x,y);
    objOfFly.set(objOfSwim.get(location));
    }

Upvotes: 0

Views: 390

Answers (1)

matt
matt

Reputation: 12346

One way I could see this being a composition problem. You could have different actions.

Monster{
   int[] location;
}

Your actions:

SwimAction{
    public void swim(Monster m, int x, int y){
        //whatever you do to update the location.
        m.location[0] += x;
        m.location[1] += y;
    }
}

Then a swim monster.

SwimMonster{
    Monster base;
    SwimAction swimAction;
    public void swim( int x, int y ){
        swimAction.swim(base, x, y);
    }
}

Similarly you could compose more actions.

SwimFlyMonster{
    Monster base;
    SwimAction s;
    FlyAction f;
    public void swim(int x, int y){
        s.swim(base, x, y);
    }
    public void fly(int x, int y){
        f.fly(base, x, y);
    }
}

Upvotes: 1

Related Questions