Search code examples
javaclass-diagram

Class Diagram - How would this reflexive relationship look?


I am doing y firsts class diagrams as part of my career, and when reading the requirements of the assignment I came to one where two of the attributes of an Animal object are the Animal's Mother and Father IF they have pedigree.

I asked the course teacher but the only thing he told me was that I was right in my assumption that it was a reflexive relationship but the following doubt remains.

-How is this implemented in code?

We haven't seen this kind of relationship before and I only discovered it by browsing StackOverflow.

Also we're managing the objects by demand, so instead of arrayLists we have been recently introduced to the use of vectors and tree maps.

This is how my class diagram looks right now.

Animal class is in the top right corner.

Padres = parents, and the justification for the multiplicity is that an Animal may or may not have both parents of just a mother/father registered.

Thanks a lot in advance.


Solution

  • I don't know if i understand the question correctly - is the code below of any help?

    public class Animal {
        private Animal padre;
        private Animal madre;
    
        // ...
        // other fields
        // ...
    
        //one of the constructors.
        public Animal(final Animal padre, final Animal madre)
        {
            this.padre = padre;
            this.madre = madre;
        }
    
        // ...
        // rest of your code
        // ...
    }
    

    or if it should be an Array then:

    //field
    private Animal[] padres;
    //constructor
    public Animal(final Animal[] padres) {
        if (padres != null) {
            if (padres.length > 2) {
                throw new IllegalStateException("Too many parents");
            }
        }
        this.padres = padres;
    }