UML diagram for Java code

I am new to Java and trying to solve some issues where I need to convert a UML diagram to Java code: I have an image of an uml document -

http://s1079.photobucket.com/albums/w513/user20121/?action=view¤t=uml.jpg

I will show you what I still have:

Q1: Write the Java version of the Entry class, assuming it has this constructor: public Entry (String name) and the getSize method is abstract. AND:

public abstract class Entry {
    private String name;

    public Entry(String name){
        this.name =  name;
    }
    public String getName()
    {
        return name;
    }
    abstract long getSize();
}

Q2: write the Java version of the File class, assuming that it has this constructor: public File (String name, long size) A:

public class File extends Entry {
    private long size;

    public File(String name, long size){
        super(name);
        this.size = size;
    }

    public long getSize(){
        return size;
    }
}

Q3: . Java- Directory, , : public Directory (String name), getSize ( ).

A: , , getSize. - , ? Q3?

: , , .

import java.util.ArrayList;

public class Directory extends Entry {

    ArrayList <Entry> entries = new ArrayList<Entry>();

    public Directory(String name)
    {
        super(name);
    }

    public long getSize(){
        long size;
        for(int i=0;i<entries.size();i++)
        {
        size +=  //don't know what to put here?
        }
        return size;
    }
}
+3
3

Q1 Q2 .

Q3:

// A Directory is an Entry and can contain an arbitrary number of other Entry objects
public class Directory extends Entry {

    // you need a collection of Entry objects, like ArrayList<Entry>
    // ArrayList<Entry> entries = ...

    function getSize() {
        long size;
        // now we calculate the sum of all sizes
        // we do not care if the entries are directories or files
        // the respective getSize() methods will automatically do the "right thing"
        // therefore: you iterate through each entry and call the getSize() method
        // all sizes are summed up
        return size;
    }

}
+1

As indicated, the first two elements are correct.

Here is how I could implement your Directory class.

import java.util.ArrayList;

public class Directory extends Entry{


ArrayList <Entry> entries = new ArrayList<Entry>();

public Directory(String name)
{
    super(name);
}

public long getSize(){
    long size = 0;
    for(int i=0;i<entries.size();i++)
    {
    //Probably something like this
    size += entries.get(i).getSize();
    }
    return size;
}
}

If your directory contains other directories, getSize of the child directory will be called to get its size.

You will need to add a control that you cannot add to the directory, or you will have an infinite loop :)

Another variant

public long getSize(){
    long size = 0;
    for( Entry e : entries)
    {
    //Probably something like this
    size += e.getSize();
    }
    return size;
}
0
source

All Articles