spx305
spx305

Reputation: 109

Convert UML class association "1 to n" to java code

I have to do reverse engineering from UML class diagram to java code. Here's an example:

enter image description here

As you can see, a SCSIController can have 1..4 DiskDrive. Can i represent it in java this way?

public class SCSIController extends Controller{
    private List disks;

    public SCSIController(){
        disks=new ArrayList();
    }

    public void addDisk(DiskDrive d){
        if(disks.size()<4 && !disks.contains(d)){
            disks.add(d);
            ………
            ………
        }else
             ……… //do something else
    }
}

Before adding a DiskDrive to SCSIController, i check that the SCSIController has less than 4 DiskDrive in his disks list. Is this the right way to code this 1 to n association?

Upvotes: 0

Views: 373

Answers (1)

qwerty_so
qwerty_so

Reputation: 36323

Basically your are correct. However, your multiplicity does not require uniqueness

enter image description here

though it will make a lot of sense :-) Going strictly with the UML spec you could omit && !disks.contains(d)) from your code. Or you add the type like shown above. (Or probably just assume that people are able to recognize that the right way.)

Side note: I think a SCSIController can as well have attached no drive. Your UML shows 1..4 so you'd need at least one drive which makes your code wrong in that respect.

Upvotes: 1

Related Questions