La Trobe University, Bendigo

EXAMINATION JUNE 2005

INT21OOP Object-Oriented Programs

Examiner:  Mary Martin                                                                 Time Allowed: 2.5 hours

            ___________________________________________________________________

Instructions to Candidates:

1.         Answer all questions.

2.         Full marks = 80.

3.         Not all questions carry equal marks.

4.         Figures to the right indicate marks.

5.         Make suitable assumptions where necessary.

6.         Clearly state any assumptions made.


Question 1

  1. If a computer language is to be considered object oriented what three fundamental concepts must be supported by the language?

  2. Identify the three major stages of object oriented development of software.
  1. Perform an initial analysis of the system described below by identifying the domain objects necessary to create the application (including internal and external data structures if necessary). Assign class names to represent the objects and identify any that you could expect to find in the Java Application Programming Interface (API). Explain why you could expect to find them in a class library or package of the Java API .

The SAMS System

La Trobe University, Bendigo has commissioned you to develop an application that will allow the staff to keep track of their studentÕs assignments.  To do this, you must maintain a database of details about each assignment.  The interface to your Student Assignment Management System (SAMS) will be a Graphical User Interface (GUI).

Each assignment is described by

The data for the application will be stored externally in files or a database (doesn't matter which). The application will load the necessary data when the program starts up. 

The SAMS must allow for displays and printouts of

The system must also allow for adding an assignment, deleting an assignment and modifying the details of an assignment.

(3 + 3 + 9 = 15 marks)

Question 2

Parts a., b., c., d., e., f. and g. of this question refer to the Java code given below. The code defines a class called BuildingDetails.

import java.io.*;

import java.util.*;

import java.awt.*;

//class to represent details about a building

public class BuildingDetails implements Comparable, Serializable{

    private String name;

    //array to store numbers of rooms, doors and windows respectively

    private int[] numbers = new int[3];

    BuildingDetails(){

        name = "Business";

        for(int i=0;i<numbers.length;i++)

                  numbers[i]=2;

    }

    BuildingDetails(String n,int r, int d, int w){

        name = n;

        numbers[0] = r;

        numbers[1] = d;

        numbers[2] = w;

      }

    public static BuildingDetails createbuildingDetails(String aLine)

                                     throws NumberFormatException{

      String name;

      int rooms, doors, windows;

      double price;

      StringTokenizer tokens;

      BuildingDetails aBuilding = null;

      if(aLine != null){

          tokens  = new StringTokenizer(aLine, ",");

          if (tokens.countTokens()==4){

              try{name = tokens.nextToken();

                  rooms = Integer.parseInt(tokens.nextToken().trim());

                  doors = Integer.parseInt(tokens.nextToken().trim());

                  windows = Integer.parseInt(tokens.nextToken().trim());

                  aBuilding = new BuildingDetails(name,rooms,doors,windows);

              }catch (NumberFormatException e){System.out.println(e + aLine);}

          }

          else

               System.out.println("Data in incorrect Format!!!!!!!");

       }

       else

           System.out.println("No data!!!!!!!");

       return aBuilding;

    }

     public void setName(String n){ name = n;}
  public void setRooms(int r){ numbers[0] = r;}
  public void setDoors(int d){ numbers[1] = d;} 
  public void setWindows(int w){ numbers[2] = w;}
  public String getName(){ return name;} 
  public int getRooms(){ return numbers[0];}
  public int getDoors(){ return numbers[1];}
  public int getWindows(){ return numbers[2];}
  public String toString(){
       return ( name +" "+numbers[0]+" "+numbers[1]+" "+numbers[2]);
  }

     public int compareTo(Object value){

        BuildingDetails a = this;

        BuildingDetails b = ((BuildingDetails)value);

        return a.name.compareTo(b.name);

    }

}

  1. In the code segment:

     public class BuildingDetails implements Comparable, Serializable{

          What does implements mean?
 

  1. The method createbuildingDetails will throw a NumberFormatException. Explain (i) what will cause the code to generate this exception and (ii) what will happen when it occurs.

  2. The method createbuildingDetails will also generate an error message saying Data in incorrect Format!!!!! . What situation will cause the code to generate this message?

  3. What are methods whose name starts with setÉ often referred to as?

  4. What are methods whose name starts with getÉ often referred to as?

  5. Using the class BuildingDetails explain the effect of the modifiers public and private.

  6. Could the class BuildingDetails be used to create a component? Briefly explain why or why not.

 

Parts h., i., j., k., l. and m. of this question refer to the Java code given on the following pages. The code defines an application class called BuildingApp and a GUI class called StatsPanel (for formatting the output in a Panel). When executed an object of type BuildingApp is created the graphical interface allows a selectable list of BuildingDetails objects (as per the class definition given in the first part of this question) to be displayed. Depending on which button object is clicked, the display will create a StatsPanel object to alternatively show the detail (numbers of rooms, doors and windows) of the selected building or the grand totals of rooms, doors and windows for all buildings in the list.

public class BuildingApp extends JFrame implements ActionListener,

                                                   ListSelectionListener{

    //------ application specific data ------

    private Vector buildingList = new Vector();

    private String fileName = "building.txt";

    private BuildingDetails building;

    private int totalRooms, totalDoors, totalWindows;

    //------ GUI data -----------------------

    private JButton listButton = new JButton("Building List ");

    private JButton detailButton = new JButton("Building Details");

    private JButton roomsButton = new JButton("Total rooms");

    private JButton doorsButton = new JButton("Total doors");

    private JButton windowsButton = new JButton("Total windows");

    private JPanel displayPanel;

    private JList displayList = new JList();

    private JScrollPane displayScroll = new JScrollPane();

    private Container cp = getContentPane();  

    public static void main(String args[]) {

    //--------------------------------------------------------

        new BuildingApp();

    }

    public BuildingApp() {

    //--------------------------------------------------------

        super("Building Statistics");

        buildingList = readRecords(fileName);

        setupGUI();

    }

    public void valueChanged(ListSelectionEvent e){

    //--------------------------------------------------------

        selectedbuilding =

      (BuildingDetails)buildingList.elementAt(displayList.getSelectedIndex());

        detailButton.setEnabled(true);

    }

 

    public void actionPerformed(ActionEvent event){

    //--------------------------------------------------------

        String category = null;

        int number = 0;

        displayPanel.removeAll();

        if (event.getSource()==listButton){

            setupDisplayList();

            displayPanel.add("Center", displayScroll);

        }

        else if (event.getSource()==detailButton){

            StatsPanel detailPanel = new StatsPanel(category,number,building);

            displayPanel.add("Center", detailPanel);

        }

        else if (event.getSource()==roomsButton){

            category = "Grand Total Number of rooms";

            number = totalRooms;

            StatsPanel statsPanel = new StatsPanel(category,number,building);

            displayPanel.add("Center", statsPanel);

        }

        else if (event.getSource()==doorsButton){

            category = "Grand Total Number of doors";

            number = totalDoors;

            StatsPanel statsPanel = new StatsPanel(category,number,building);

            displayPanel.add("Center", statsPanel);

            }

        else if (event.getSource()==windowsButton){

            category = "Grand Total Number of windows";

            number = totalWindows;

            StatsPanel statsPanel = new StatsPanel(category,number,building);

            displayPanel.add("Center", statsPanel);

        }

        detailButton.setEnabled(false);

        displayPanel.validate();

   }

   private void setupGUI(){

   //--------------------------------------------------------

        cp.setLayout(new BorderLayout());

        JPanel buttonPanel = new JPanel();

        buttonPanel.setLayout(new GridLayout(5,1));

        buttonPanel.add(listButton);

        buttonPanel.add(detailButton);

        buttonPanel.add(roomsButton);

        buttonPanel.add(doorsButton);

        buttonPanel.add(windowsButton);       

        cp.add("East",buttonPanel);

        displayPanel = new JPanel();

        displayPanel.setLayout(new BorderLayout());

        buildStats();

        setupDisplayList();

        displayPanel.add("Center", displayScroll);

        cp.add("Center",displayPanel);

        displayList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        listButton.addActionListener(this);

        detailButton.addActionListener(this);

        roomsButton.addActionListener(this);

        doorsButton.addActionListener(this);

        windowsButton.addActionListener(this);              

        detailButton.setEnabled(false);

        setBounds(100,100,450,200); 

        setVisible(true);

    }

 

   private void setupDisplayList(){

    //--------------------------------------------------------

        displayList = new JList(buildingList);

        displayList.setBorder(BorderFactory.createTitledBorder(

"Building List"));       

        displayScroll.getViewport().add(displayList);

        displayList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        displayList.addListSelectionListener(this);       

    }

    private Vector readRecords(String fileName){

    //---------------------------------------------------------

        String aLine;

        Vector thisList = new Vector();      

        try {

            BufferedReader br = new BufferedReader(new FileReader(fileName));

            while ((aLine = br.readLine()) != null){

                BuildingDetails newBuilding =

                BuildingDetails.createbuildingDetails(aLine);

                if (newBuilding != null){

                    thisList.add(newBuilding);

                    System.out.println(newBuilding);

                }

            }

            br.close();

        }

        catch (FileNotFoundException e) {

            System.out.println(e);

        }

        catch (IOException e) {

            System.out.println(e);

        }

        return thisList;

    }

    private void buildStats(){

    //--------------------------------------------------------- 

        BuildingDetails building = null;

        totalRooms = totalDoors = totalWindows = 0;

        for (Iterator i=buildingList.iterator(); i.hasNext();){

            building = (BuildingDetails)i.next();

            totalRooms = totalRooms + building.getRooms();

            totalDoors = totalDoors + building.getDoors();

            totalWindows = totalWindows + building.getWindows();          

        }

    }

}

(ÉQuestion 2 cont)

public class StatsPanel extends JPanel{

    private BuildingDetails theBuilding;

    private String theCategory;

    private int theNumber;

    public StatsPanel(String category, int number, BuildingDetails building){

    //----------------------------------

        setBackground(Color.white);

        theCategory = category;

        theNumber = number;

        theBuilding = building;

        repaint();

    }

    public void paintComponent(Graphics g){

    //----------------------------------

        super.paintComponent(g);

        int inc = 40, hVal=20, vVal = 0;

        if(theCategory!=null){

            g.setFont(new Font("Helvetica", Font.BOLD, 14));

            if (theNumber >=0)

               g.drawString(theCategory+" is "+theNumber, hVal, vVal+inc*2);

            else

               g.drawString(theCategory, hVal, vVal+inc*2);

        }

        else

            if(theBuilding!=null){

               String buildingName;

               buildingName = theBuilding.getName();

               g.setFont(new Font("Helvetica", Font.BOLD, 14));

               g.drawString("Building Name: "+buildingName, hVal, vVal+inc*2);          

               g.setFont(new Font("Helvetica", Font.PLAIN, 12));

               g.drawString("has "+theBuilding.getDetails(),hVal, vVal+inc*3);           

            }

    }

}

  1. Draw a diagram that shows the graphical interface of the program presented to the user when it is initially executed. Label the types (eg button etc) of the visual components created along with showing the approximate placement or layout of those components in the applicationÕs base window.

i.      The BuildingApp class is an example of event-driven programming, where the code executed is determined by events that occur as the program executes.

i.      Identify the three essential code segments in the BuildingApp class which implement the event handling mechanism.

ii.     Explain how the event handling mechanism works.

 

  1. BuildingApp can respond to action events and list selection events. Draw diagrams (with annotations where necessary) showing only the changes to the programÕs display after each of the following situations:

i.      A building in the displayed building list is selected

ii.     The listButton has been clicked

iii.   The detailButton has been clicked and a building in the building list is selected

iv.   The detailButton has been clicked and a building in the building list is not selected

v.     The roomsButton has been clicked

  1. The body of the actionPerformed method contains one large multiway ifÉelse statement. Identify a behavioural design pattern that could be used to eliminate this statement and the actionperformed method. Why would you want to do this?
  1. Some code in the buildStats method is also an example of a behavioural design pattern that you have studied this semester. Identify the code in that method and the design pattern it implements.
  1. The paintComponent method of the StatsPanel class contains an ifÉelse statement to allow for alternative views of the StatsPanel object. Identify a creative design pattern that would eliminate the need for this conditional statement. Why would you want to eliminate the conditional statement?

(1  + 3 + 2 + 1 + 1 + 2 + 2 +

4 + (3+2) + (2+2+2+2+2) + 3 + 3 + 3

= 40 marks)

 

 

Question 3

  1. The code below was demonstrated in a lecture this semester as an example of  Java thread concurrency. Identify the code segments that implement thread concurrency and describe what happens when the program is executed.

public class ThreadedBallWorld extends JFrame{

      public static final int FWIDTH = 600;

      public static final int FHEIGHT = 400;

      private static int ballArraySize = 10;

      private Ball []balls;

      private int counter = 0;

public static void main (String argv[]){

         ThreadedBallWorld world = new ThreadedBallWorld(10);

         world.show();

      }

      public ThreadedBallWorld(int size){

         setSize(FWIDTH,FHEIGHT);

         setTitle("Multi Ball World");

         addMouseListener(new BallListener());

         setBackground(Color.white);

         ballArraySize = size;

         balls = new Ball[ballArraySize];

         for (int i = 0; i < ballArraySize; i++){

            balls[i] = new Ball(10,15,5);

            balls[i].setColor(new Color((float)Math.random(),

                  (float)Math.random(),(float)Math.random()));

            balls[i].setMotion(3.0+i,6.0-i);                           

         }

         Thread ballThread = new BallThread();

         ballThread.start();

      }

      public void paint(Graphics g){

         super.paint(g);

         for (int i = 0; i < ballArraySize; i++){

            balls[i].paint(g);                                   

         }

      }

      private class BallThread extends Thread{

         public void run(){

            while (true){

               for (int i = 0; i < ballArraySize; i++){

                  theBalls[i].move();

                  if((balls[i].x()<0)||(balls[i].x()>FWIDTH))

                     balls[i].setMotion(balls[i].xMotion()

   ,balls[i].yMotion());

                  if((balls[i].y()<0)||(balls[i].y()>FHEIGHT))

                     balls[i].setMotion(balls[i].xMotion()

   ,-balls[i].yMotion());

                  }

                  repaint();

                  try{

                      sleep(50);

                  } catch (InterruptedException e){}

               }

            }

         }

      }

 

private class BallListener extends MouseAdapter{

         public void mousePressed (MouseEvent e){

            for (int i = 0; i < ballArraySize; i++)

               balls[i].moveTo(e.getX(), e.getY());

         }

     }

}

  1. Java threads provide concurrency within Java programs, but are not separate concurrent processes under the control of the operating system. Briefly explain how Java threads work.

  2. Give two reasons why threads are used in Java programs.

 (6 + 2 + 2 = 10 marks)

Question 4

  1. Briefly define the term Software Engineering, its main objectives and its relationship to the Object-Oriented approach to programming.

  2. What requirements must be met if a class is to be considered as a component? Are the awt classes from the JavaÕs Application Programming Interface (API) components?

  3. Data represented in XML format allows it to be portable and structured at the same time. Briefly explain how this is possible.

  4. In 2000 the international Standards organization, OMG (Object Management Group) proposed the MDA (Model Driven Architecture) to replace OMA (Object Management Architecture) as an approach to software engineering. Briefly explain what this means and what led to this major change.

(5 + 4 + 3  + 3 = 15 marks)