file:///home/joans/documents/docencia/es2/curs...
|
|
- Bathsheba Pierce
- 6 years ago
- Views:
Transcription
1 GRASP GRASP stands for General Responsibility Assignment Solution Patterns. There are nine pattern in the Layman text: Information Expert (Expert) Creator High Cohesion Low Coupling Controller Polymorphism Pure Fabrication Indirection Protected Variations Information Expert Name: Information Expert Problem: What is the general principle of assigning responsibilities to a class? Once the classes present in a problem description have been identified, how do we determine which class handles a responsibility. Solution: Assign a responsibility to the information expert, the class that has the information necessary to fulfill the responsibility. Discussion: Consider, 1 1 * * Course Student WorkIte which class should determine the final mark the student receives in a course. While the WorkItem class can determine the value of an individual items, they can not determine the final mark. The Student class should be assigned this responsibility since it knows about all of the work items. The Student class will rely on the WorkItem class to determine the individual marks. The Expert pattern has a real world analogy, who do you ask about X, you ask the expert who knows about X. Information Expert Examples In the Resistor design example, some of the responsibilities are: Who is responsible for maintaining the collection of resistors, and for accessing selected ranges of the resistor? Who is responsible for calculating the voltage divisor ratio? The Information expert design pattern can be used to assign the above responsibilities. Since the ResistorManager stores the list of resistors (i.e., it knows about the resistors), it should be responsible for selecting a range of resistors. The voltage divider ration must be calculated by the VoltageDivider since this class knows about the two resistors that form the voltage divider. More Information Expert Examples Consider the following responsibilities from paint estimator program: 1 of 22 09/12/ :23 AM
2 Who should calculate the amount of paint need to cover a given area? Who should be responsible calculating the amount of paint need for a wall? Since the Paint class knows about the coverage, it should be responsible for calculating the required paint for a given area. A wall knows about its paint, its area, and the list of doors and windows that a part of the wall, thus it has all the information necessary to calculate the amount of paint required. Marking System Example The marking system can be modeled with the following domain classes: WorkItem, MarkingScheme, Student, and Course. Consider the following responsibilities: the calculation of the final grade for a student, editing a working item, the report of all the grades in a class, a list of all the student name and numbers in the class, Using the Expert design pattern, decide which class if possible of the domain class should be assigned the given responsibility. If no domain class is possible, suggest a software class that should be responsible. Creator Name: Creator Problem: Which class should be responsible for creating a new instance of some class. Since creating objects is a common activity, having some patterns help the quality of the design. Solution: Assign class B the responsibility of creating and instance of class A if: B aggregates A objects, B contains A objects, B closely uses A objects, B has data needed to create an A object. Discussion: The last point is also an application of the Information Expert Design pattern, since an Expert knows about the information needed to create objects of class A. Low Coupling Name: Low Coupling Problem: How to support low dependency, low change impact, and increase reuse? Solution: Assign a responsibility so that coupling remains low. 2 of 22 09/12/ :23 AM
3 Discussion: A class with strong coupling relies on many other classes. This can result in: changes in the class propagate to changes elsewhere, a class that is hard to understand in isolation, a class that is hard to reuse. Low coupling in Java The low coupling pattern is an evaluation principle. It is applied so that all design decisions can be evaluated. In Java, common forms of coupling from type X to type Y include: Type X contains an attribute of type Y, Type X has a method that references a type Y object, Type X is a direct or indirect subclass of type Y, Type Y is an interface that type X implements. Low coupling Low coupling supports classes that are more independent, which reduces the impact of change. Subclasses should be created very carefully since the subclass is highly coupled to the super class. Extreme low coupling should be avoided since it can result in in-cohesive and bloated classes. The low coupling pattern should not be used as an excuse to avoid common utility classes that are found in java.util.*. When a class is stable (i.e., not likely to change) then the harm of coupling is greatly reduced. The real problem of coupling is not the linkage, but the fact that changes to couple classes affect each other. Low coupling Exercise Consider the method addtrack for an Album class, two possible methods are: addtrack( Track t ) and addtrack( int no, String title, double duration ) Which method reduces coupling? The second one does, since the class using the Album class does not have to know a Track class. In general, parameters to methods should use base types (int, char...) and classes from the java.* packages. Coupling between Wall and PaintAmountReporter Consider the reportpaint method. public void reportpaint( PaintAmountReporter reporter ) { reporter.addpaint( paint.getcolour(), paintamount() ); for( int i = 0 ; i < openings.size(); i++ ) { Opening o = openings.get( i ); reporter.addpaint( o.gettrimpaint().getcolour(), o.trimarea()); Is the coupling between PaintAmountReporter and Wall good or bad? How could it be removed? High Cohesion 3 of 22 09/12/ :23 AM
4 Name: High Cohesion Problem: How to keep objects focused, understandable, and manageable? Solution: Assign responsibilities so that cohesion remains high. Discussion: Cohesion measures the degree that the responsibilities in a class are related and if they are focused on the same goals. A software component with highly functionally related responsibilities is cohesive. This class does not attempt to do too much. A class with low cohesion does many unrelated things, or does too much work. A class with low cohesion suffers from the following problems: hard to comprehend, hard to reuse, hard to maintain, not robust. Class with low cohesion often represent a very large grain of abstraction. They have taken on too many responsibilities. Cohesion Examples Examples illustrating varying degrees of functional cohesion are: very low cohesion - A class is solely responsible for many things in very different functional areas. If most programs are implemented in one class, then that class would have very low cohesion. low cohesion - A class has sole responsibility for a complex task in one functional area. high cohesion - A class has moderate responsibilities in one functional area and collaborates with other classes to fulfill the task. High Cohesion Classes with high cohesion generally have a relatively small number of methods. The methods are related functionally. A real world analogy of low cohesion is a person that takes on too many unrelated responsibilities, especially ones that should properly be delegated to others. In any design decision both coupling and cohesion should be considered. Coupling and Cohesion Exercise Identify coupling and cohesion issues with the following code. import java.util.arraylist; import java.util.iterator; examples/numbersstatscommand.java public class NumbersStatsCommand { public static void main( String[] args ) { NumberSequence seq = new NumberSequence(); int i; for( i = 0 ; i < args.length; i++ ) { try { seq.appendnumber( Double.parseDouble( args[i] ) ); 4 of 22 09/12/ :23 AM
5 catch( NumberFormatException ex ) { break; for(; i < args.length; i++ ) { System.out.println( args[i] + " " + seq.calculate( args[i] ) ); class NumberSequence { private ArrayList<Double> list; public NumberSequence() { this.list = new ArrayList<Double>(); public void appendnumber( double d ) { list.add( new Double( d ) ); public double calculate( String cmd ) { if ( cmd.equals("sum") ) { double sum = 0.0; Iterator<Double> dit = list.iterator(); while ( dit.hasnext() ) { sum += dit.next().doublevalue(); return sum; else if ( cmd.equals("min") ) { Iterator<Double> dit = list.iterator(); double min = dit.next().doublevalue(); while ( dit.hasnext() ) { double d = dit.next().doublevalue(); if ( d < min ) { min = d; return min; return 0.0; Any bad practices? Coupling and Cohesion Improvements import java.util.arraylist; import java.util.iterator; examples/numbersstatscommandv2.java public class NumbersStatsCommandV2 { public static void main( String[] args ) { NumberSequence seq = new NumberSequence(); int i; for( i = 0 ; i < args.length; i++ ) { try { seq.appendnumber( Double.parseDouble( args[i] ) ); catch( NumberFormatException ex ) { break; for(; i < args.length; i++ ) { if ( args[i].equals("sum") ) { 5 of 22 09/12/ :23 AM
6 System.out.println( "sum: " + seq.sum() ); else if ( args[i].equals("min") ) { System.out.println( "min: " + seq.min() ); else { System.out.println( "unknown command: " + args[i] ); class NumberSequence { private ArrayList<Double> list; public NumberSequence() { this.list = new ArrayList<Double>(); public void appendnumber( double d ) { list.add( new Double( d ) ); public double sum() { double s = 0.0; Iterator<Double> dit = list.iterator(); while ( dit.hasnext() ) { s += dit.next().doublevalue(); return s; public double min() { Iterator<Double> dit = list.iterator(); double m = dit.next().doublevalue(); while ( dit.hasnext() ) { double d = dit.next().doublevalue(); if ( d < m ) { m = d; return m; Bad coupling and cohesion can result from assigning too many responsibilities to the same class or from assigning the same responsibility to more than one class. In NumbersStatsCommand, the responsibility to parsing the command line has been assigned to two classes. Implementation Improvements public class NumbersStatsCommandV3 { examples/numbersstatscommandv3.java public static void main( String[] args ) { NumberSequence seq = new NumberSequence(); int i; for( i = 0 ; i < args.length; i++ ) { try { seq.appendnumber( Double.parseDouble( args[i] ) ); catch( NumberFormatException ex ) { break; if ( i == 0 ) { System.out.println( "no numbers" ); System.exit( 1 ); 6 of 22 09/12/ :23 AM
7 for(; i < args.length; i++ ) { if ( args[i].equals("sum") ) { System.out.println( "sum: " + seq.sum() ); else if ( args[i].equals("min") ) { System.out.println( "min: " + seq.min() ); else { System.out.println( "unknown command: " + args[i] ); class NumberSequence { private double currentsum; private double currentmin; public NumberSequence() { this.currentsum = 0.0; // Double.MAX_VALUE is the maximum double value // what is the benefit of this assignment? this.currentmin = Double.MAX_VALUE; public void appendnumber( double d ) { currentsum += d; if ( d < currentmin ) { currentmin = d; public double sum() { return currentsum; public double min() { return currentmin; Reduced coupling, enables a simpler and more efficient implementation, The client classes are not affected by this change. Another cohesion and coupling exercise Identify the low cohesion and high coupling in the following program. import java.util.regex.pattern; import java.util.regex.matcher; import java.util.scanner; cc/generatereport.java public class GenerateReport { private static final Pattern pat = Pattern.compile( "<(-?\\d+),(-?\\d+)>" ); private double maxx = Double.MIN_VALUE; private double maxy = Double.MIN_VALUE; private double minx = Double.MAX_VALUE; private double miny = Double.MAX_VALUE; public void processdata() { Scanner sc = new Scanner(System.in); while( sc.hasnextline() ) { String line = sc.nextline(); Matcher matcher = pat.matcher( line ); double x, y; 7 of 22 09/12/ :23 AM
8 try { if ( matcher.matches() ) { x = Double.parseDouble( matcher.group(1)); y = Double.parseDouble( matcher.group(2)); if ( x < minx ) minx = x; if ( y < miny ) miny = y; if ( x > maxx ) maxx = x; if ( y > maxy ) maxy = y; catch( NumberFormatException ex ) { continue; // discard bad line public void genreport() { double largestmax = Math.max( maxx, maxy); double smallestmin = Math.min( minx, miny); double dist = Math.hypot(maxX-minX,maxY-minY); System.out.println("Largest maximum is " + largestmax ); System.out.println("Smallest minimum is " + smallestmin ); System.out.println("Largest distance is " + dist ); public static void main( String[] args ) { GenerateReport rep = new GenerateReport(); rep.processdata(); rep.genreport(); Improved version The class CoordinateData is only responsible for the coordinate information and any calculations on this information. It does not deal with handling input or producing the report. public class CoordinateData { private double maxx = Double.MIN_VALUE; private double maxy = Double.MIN_VALUE; private double minx = Double.MAX_VALUE; private double miny = Double.MAX_VALUE; cc/coordinatedata.java public void updatecoordinatedata( double x, double y ) { if ( x < minx ) minx = x; if ( y < miny ) miny = y; if ( x > maxx ) maxx = x; if ( y > maxy ) maxy = y; public double getlargestmax() { return Math.max( maxx, maxy); public double getsmallestmin() { return Math.min( minx, miny); public double getlargestdist() { return Math.hypot(maxX-minX,maxY-minY); // Anything missing from this class? Classes with high cohesion generally have a relatively small number of methods. The methods are related functionally. 8 of 22 09/12/ :23 AM
9 These conditions are true for the CoordinateData class. Parsing the coordinate data The responsibility of parsing the data is now handled by the ParseCoordinateStream class. It does not handle any calculation. import java.io.inputstream; import java.util.scanner; import java.util.regex.pattern; import java.util.regex.matcher; cc/parsecoordinatestream.java class ParseCoordinateStream { private static final Pattern pat = Pattern.compile( "<(-?\\d+),(-?\\d+)>" ); private InputStream instream; private Scanner scanner; private double x, y; public ParseCoordinateStream( InputStream instream ) { this.instream = instream; this.scanner = new Scanner( instream ); public boolean fetchnextpair() { while ( scanner.hasnextline() ) { String line = scanner.nextline(); Matcher matcher = pat.matcher( line ); try { if ( matcher.matches() ) { x = Double.parseDouble( matcher.group(1)); y = Double.parseDouble( matcher.group(2)); return true; catch( NumberFormatException ex ) { continue; // discard bad line return false; public double getx() { return x; public double gety() { return y; public static void main(string args[] ) { ParseCoordinateStream parser = new ParseCoordinateStream(System.in); CoordinateData cd = new CoordinateData(); while ( parser.fetchnextpair() ) { cd.updatecoordinatedata( parser.getx(), parser.gety() ); System.out.println("Largest maximum is " + cd.getlargestmax() ); System.out.println("Smallest minimum is " + cd.getsmallestmin() ); System.out.println("Largest distance is " + cd.getlargestdist() ); Again this class has a small number of functionally related methods, thus is cohesion is high. Push model 9 of 22 09/12/ :23 AM
10 Further reduction in coupling can occur with an implementation of a class the supports the push model of data processing. In the push model the data is feed to the consuming class. import java.io.inputstream; cc/pushcoordinates.java class PushCoordinates { private ParseCoordinateStream pullcoords; public PushCoordinates( InputStream instream ) { this.pullcoords = new ParseCoordinateStream( instream ); public interface Push { public void push( double x, double y ); public void pushcoordinates( Push p ) { while ( pullcoords.fetchnextpair() ) { p.push( pullcoords.getx(), pullcoords.gety() ); public static void main(string args[] ) { PushCoordinates pusher = new PushCoordinates(System.in); final CoordinateData cd = new CoordinateData(); pusher.pushcoordinates( new PushCoordinates.Push() { public void push( double x, double y ) { cd.updatecoordinatedata(x, y); ); System.out.println("Largest maximum is " + cd.getlargestmax() ); System.out.println("Smallest minimum is " + cd.getsmallestmin() ); System.out.println("Largest distance is " + cd.getlargestdist() ); Any class that needs data, implements the Push interface. Coupling can be easily reduce, how? Controller Name: Controller Problem: Which first object beyond the UI layer receives and coordinates a system operations? Solution: Assign responsibility for receiving events to either: a class the represents the system, or a class the represents the particular use case. Discussion: Controller classes provides the glue between the system events and software model. Since the type of use case tends to change, the classes can change without affecting the rest of the system (i.e., coupling is reduced). The UI classes only interact with the controller classes. The controller classes normally delegates most of the work to other classes in the system. 10 of 22 09/12/ :23 AM
11 Entity, Boundary, and Control Objects Entity objects are instances of domain classes. Boundary objects represent the interaction between actors and the system Control objects are in charge of realizing use cases. Actors interact with boundary objects. Boundary object communicate and are controlled by control objects (Controller design pattern). Control object interact with entity objects to accomplish the goals of the system. Grouping objects into entity, boundary, and control classes provides a structure that aids and improves the software design of a system. Boundary objects can represent UI components, control objects are responsible for managing use cases, and entity objects represent the real world. HiLo Game In the HiLo game, a player has to guess a randomly selected number between a low and a high number. If their guess is too high or too low or correct they are informed, The goal of the game is to guess the correct number in a limited number of trys. The games should track the number of player wins and the total number of games played. The player should also be given the opportunity to to choose the low and high numbers. PlayGame Use Case Use Case Name: PlayGame Actor: HiLo Player Precondition: A game has started with a selected range and a randomly chosen number to guess. The user has 10 guesses. Flow of events: Basic Path A hilo game has started with a selected range and a randomly chosen number to be guess. While the user still has guesses available: 1. The user is prompted to enter a guess. 2. If the user enters a number, then 1. if the guessed number is higher than the correct number, report that the guess is higher, and return to step if the guessed number is lower than the correct number, report that the guess is lower, and return to step if the guessed number matches the choose number, report the success and the use case ends. 3. If the user quits, the use case ends. The use case ends. Postcondition: A user has either won, lost or quit the game. For this use case: is the use case too complicated, is the use case too simple, does the post condition describe a real change, is the interaction too specific to an interface technology, are the any problems, is there anything missing, and can the description be improved (i.e., made to read better). 11 of 22 09/12/ :23 AM
12 StartGame Use Case Use Case Name: StartGame Actor: HiLo Player Precondition: At least one hilo game has occurred. Flow of events: Basic Path A user requests the statistics of the last set of games played. The system displays the number of wins and the number of games played. The use case ends. Postcondition: None For this use case: is the use case too complicated, is the use case too simple, does the post condition describe a real change, is the interaction too specific to an interface technology, are the any problems, is there anything missing, and can the description be improved (i.e., made to read better). StartGame Use Case Use Case Name: StartGame Actor: HiLo Player Precondition: None Flow of events: Basic Path The user is informed that a new games is starting and asked to select the low number and high number. While the user has not correctly entered the low and high numbers: 1. The user is prompted to enter the low number and high number. 2. If the user enters valid numbers, the use case ends. 3. If the user requests to quit, the game stops, and the use case ends. The use case ends. Postcondition: The range of numbers to guess has been selected. For this use case: is the use case too complicated, is the use case too simple, does the post condition describe a real change, is the interaction too specific to an interface technology, are the any problems, is there anything missing, and can the description be improved (i.e., made to read better). HiLoGame (entity) The state of a HiLo can be modeled by: package hilo; hilo/hilo/hilogame.java import java.util.random; public class HiLoGame { private static Random random = new Random(); 12 of 22 09/12/ :23 AM
13 private int high, low; private int range; private int guess; private int guesscount; private int nogames; private int nowins; public HiLoGame( int low, int high ) { this.low = low; this.high = high; this.range = (high-low) + 1; this.nogames = 0; this.nowins = 0; newgame(); public void newgame() { guesscount = 0; guess = random.nextint( range ) + low; nogames++; /* * Return 0 if the guess is correct, > 0 if too high, * and < 0 if too low. */ public int makeguess( int userguess ) { if ( userguess == guess ) { nowins++; return 0; guesscount++; return userguess - guess; public int numguesses() { return guesscount; public int numwins() { return nowins; public int numgames() { return nogames; Does this class do one thing, and is it done well? How many other classes does it depend on? StartHiLoGame (control class) This class implements the StartHiLoGame use case, and is an example of the Controller pattern. package text; hilo/text/starthilogame.java import hilo.hilogame; import java.util.scanner; public class StartHiLoGame { private int defaultlo = 0; private int defaulthi = 100; /* 13 of 22 09/12/ :23 AM
14 * Return a HiLoGame or null to indicate end of game. */ public HiLoGame start() { Scanner scan = new Scanner( System.in ); System.out.println("Welcome to HiLo"); do { System.out.println("Please pick the guessing range [0 100] or quit"); String line = scan.nextline(); Scanner sl = new Scanner( line ); int hi = defaulthi; int lo = defaultlo; if ( sl.hasnextint() ) { lo = sl.nextint(); if ( sl.hasnextint() ) { hi = sl.nextint(); System.out.println("Starting game with " + lo + " " + hi); return new HiLoGame( lo, hi ); else if ( sl.hasnext() ) { String cmd = sl.next(); if ( cmd.equals( "quit" ) ) { System.out.println("quitting"); return null; else { System.out.println("Starting game with " + lo + " " + hi); return new HiLoGame( lo, hi ); while( true ); Does this class do one thing, and is it done well? How many other classes does it depend on? PlayHiLoGame (control class) This class implements the PlayHiLoGame use case, and is an example of the Controller pattern. package text; hilo/text/playhilogame.java import hilo.hilogame; import java.util.scanner; public class PlayHiLoGame { private HiLoGame game; public PlayHiLoGame( HiLoGame game ) { this.game = game; public boolean play() { Scanner scan = new Scanner(System.in); while( game.numguesses() <= 10 ) { System.out.print( "Enter a guess: "); String line = scan.nextline(); Scanner sl = new Scanner( line ); if ( sl.hasnextint() ) { int guess = sl.nextint(); int result = game.makeguess( guess ); if ( result == 0 ) { System.out.println("Correct guess, you win"); break; 14 of 22 09/12/ :23 AM
15 else if ( result > 0 ) { System.out.println("too high"); else { System.out.println("too low"); int rem = 10 - game.numguesses(); System.out.println(rem + " trys left"); else if ( sl.hasnext() ) { String cmd = sl.next(); if ( cmd.equals("quit") ) { return false; System.out.println("Invalid command, only quit accepted"); else { System.out.println("empty line"); return true; Does this class do one thing, and is it done well? How many other classes does it depend on? ReportStatstHiLoGame (control class) This class implements the ReportStatstHiLoGame use case, and is an example of the Controller pattern. package text; hilo/text/reportstatsthilogame.java import hilo.hilogame; public class ReportStatstHiLoGame { private HiLoGame game; public ReportStatstHiLoGame( HiLoGame game ) { this.game = game; public void report() { int wins = game.numwins(); int games = game.numgames(); System.out.println( "won " + wins + " out of " + games ); Does this class do one thing, and is it done well? How many other classes does it depend on? HiLoGameSystem (control class) This class implements the system and is an example of the Controller pattern. package text; hilo/text/hilogamesystem.java import hilo.hilogame; public class HiLoGameSystem { public static void main( String[] args ) { StartHiLoGame startgame = new StartHiLoGame(); while ( true ) { HiLoGame game = startgame.start(); 15 of 22 09/12/ :23 AM
16 if ( game == null ) break; PlayHiLoGame playgame = new PlayHiLoGame( game ); ReportStatstHiLoGame statsgame = new ReportStatstHiLoGame(game); while( playgame.play() ) { statsgame.report(); game.newgame(); Does this class do one thing, and is it done well? How many other classes does it depend on? HiLo Game Class Diagram Comment on the coupling and cohesion of the HiLo game implementation. Swing version of HiLo A screen shot of the the HiLo game implemented with swing is: 16 of 22 09/12/ :23 AM
17 HiLoControl (control) package gui; hilo/gui/hilocontrol.java import hilo.hilogame; public class HiLoControl { public HiLoControl( HiLoApp gui ) { this.gui = gui; this.game = new HiLoGame(0, 100); private HiLoApp gui; private HiLoGame game; public void playgame( int guess ) { int result = game.makeguess( guess ); if ( result == 0 ) { gui.displayplayresult("you Win, New game"); int wins = game.numwins(); int games = game.numgames(); gui.appendscoreresults( "won " + wins + " out of " + games + "\n" ); game.newgame(); else { int remaining = 10 - game.numguesses(); if ( remaining <= 0 ) { gui.displayplayresult("too many trys, New game"); int wins = game.numwins(); int games = game.numgames(); gui.appendscoreresults( "won " + wins + " out of " + games + "\n" ); game.newgame(); else { if ( result < 0 ) { gui.displayplayresult("too low, trys " + remaining + " left"); else { gui.displayplayresult("too high, trys " + remaining + " left"); 17 of 22 09/12/ :23 AM
18 public void setrange( int hi, int low ) { game = new HiLoGame( low, hi ); gui.displayplayresult( "Guess a number between " + low + " " + hi ); public static void main( String args[] ) { final HiLoApp app = new HiLoApp(); HiLoControl control = new HiLoControl( app ); app.setcontrol( control ); java.awt.eventqueue.invokelater(new Runnable() { public void run() { app.setvisible(true); ); Does this class do one thing, and is it done well? How many other classes does it depend on? HiLoApp (boundary) /* * To change this template, choose Tools Templates * and open the template in the editor. */ hilo/gui/hiloapp.java /* * App.java * * Created on Oct 31, 2009, 6:50:26 PM */ package gui; /** * rod */ public class HiLoApp extends javax.swing.jframe { private HiLoControl control; public void setcontrol( HiLoControl control ) { this.control = control; public void displayplayresult( String msg ) { playresultfield.settext( msg ); public void appendscoreresults( String msg ) { scoretextarea.append( msg ); /** Creates new form App */ public HiLoApp() { initcomponents(); /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. 18 of 22 09/12/ :23 AM
19 // <editor-fold defaultstate="collapsed" desc="generated Code">//GEN-BEGIN:initComponents private void initcomponents() { toppanel = new javax.swing.jpanel(); frametitle = new javax.swing.jlabel(); playform = new javax.swing.jpanel(); playinputform = new javax.swing.jpanel(); guesslabel = new javax.swing.jlabel(); guessfield = new javax.swing.jtextfield(); guessbutton = new javax.swing.jbutton(); playresultfield = new javax.swing.jlabel(); rangeform = new javax.swing.jpanel(); rangebutton = new javax.swing.jbutton(); highform = new javax.swing.jpanel(); highlabel = new javax.swing.jlabel(); highfield = new javax.swing.jtextfield(); lowform = new javax.swing.jpanel(); lowlabel = new javax.swing.jlabel(); lowfield = new javax.swing.jtextfield(); scoreform = new javax.swing.jpanel(); jscrollpane1 = new javax.swing.jscrollpane(); scoretextarea = new javax.swing.jtextarea(); setdefaultcloseoperation(javax.swing.windowconstants.exit_on_close); settitle("hilo"); // NOI18N setbackground(new java.awt.color(48, 219, 231)); setbounds(new java.awt.rectangle(0, 0, 100, 90)); setcursor(new java.awt.cursor(java.awt.cursor.default_cursor)); setname("top_frame"); // NOI18N getcontentpane().setlayout(new java.awt.gridlayout(1, 1)); toppanel.setbackground(new java.awt.color(173, 240, 203)); toppanel.setborder(javax.swing.borderfactory.createemptyborder(5, 5, 5, 5)); toppanel.setmaximumsize(new java.awt.dimension(500, 600)); toppanel.setminimumsize(new java.awt.dimension(300, 400)); toppanel.setpreferredsize(new java.awt.dimension(300, 400)); toppanel.setlayout(new javax.swing.boxlayout(toppanel, javax.swing.boxlayout.page_axis)); frametitle.sethorizontalalignment(javax.swing.swingconstants.center); frametitle.setlabelfor(this); frametitle.settext("hilo Game"); frametitle.setalignmentx(0.5f); frametitle.setborder(javax.swing.borderfactory.createemptyborder(1, 1, 1, 1)); frametitle.sethorizontaltextposition(javax.swing.swingconstants.leading); toppanel.add(frametitle); playform.setborder(javax.swing.borderfactory.createtitledborder("play")); playform.setopaque(false); playform.setlayout(new javax.swing.boxlayout(playform, javax.swing.boxlayout.page_axis)); playinputform.setopaque(false); guesslabel.sethorizontalalignment(javax.swing.swingconstants.left); guesslabel.setlabelfor(guessfield); guesslabel.settext("guess"); guesslabel.setalignmenty(0.0f); playinputform.add(guesslabel); guessfield.setcolumns(10); playinputform.add(guessfield); guessbutton.settext("play"); guessbutton.setminimumsize(new java.awt.dimension(70, 29)); guessbutton.setpreferredsize(new java.awt.dimension(100, 29)); guessbutton.setrequestfocusenabled(false); guessbutton.addactionlistener(new java.awt.event.actionlistener() { public void actionperformed(java.awt.event.actionevent evt) { 19 of 22 09/12/ :23 AM
20 guessbuttonactionperformed(evt); ); playinputform.add(guessbutton); playform.add(playinputform); playresultfield.settext("guess a number between 0 and 100"); playresultfield.setalignmentx(0.5f); playform.add(playresultfield); toppanel.add(playform); rangeform.setbackground(new java.awt.color(227, 231, 38)); rangeform.setborder(javax.swing.borderfactory.createtitledborder("range")); rangeform.setopaque(false); rangeform.setlayout(new javax.swing.boxlayout(rangeform, javax.swing.boxlayout.page_axis)); rangebutton.settext("set Guess Range"); rangebutton.addactionlistener(new java.awt.event.actionlistener() { public void actionperformed(java.awt.event.actionevent evt) { rangebuttonactionperformed(evt); ); rangeform.add(rangebutton); highform.setborder(javax.swing.borderfactory.createemptyborder(5, 1, 1, 1)); highform.setopaque(false); highlabel.settext("high Guess"); highlabel.sethorizontaltextposition(javax.swing.swingconstants.left); highform.add(highlabel); highfield.setcolumns(10); highfield.sethorizontalalignment(javax.swing.jtextfield.left); highfield.settext("100"); highform.add(highfield); rangeform.add(highform); lowform.setborder(javax.swing.borderfactory.createemptyborder(1, 1, 1, 1)); lowform.setopaque(false); lowlabel.settext("low Guess"); lowlabel.sethorizontaltextposition(javax.swing.swingconstants.left); lowform.add(lowlabel); lowfield.setcolumns(10); lowfield.settext("0"); lowform.add(lowfield); rangeform.add(lowform); toppanel.add(rangeform); scoreform.setborder(javax.swing.borderfactory.createtitledborder("scores")); scoreform.setopaque(false); scoreform.setlayout(new java.awt.gridlayout(1, 1)); scoretextarea.setcolumns(20); scoretextarea.setrows(10); jscrollpane1.setviewportview(scoretextarea); scoreform.add(jscrollpane1); toppanel.add(scoreform); getcontentpane().add(toppanel); 20 of 22 09/12/ :23 AM
21 pack(); // </editor-fold>//gen-end:initcomponents private void guessbuttonactionperformed(java.awt.event.actionevent evt) {//GEN-FIRST:event_guessButtonActionPerformed if ( control == null ) return; String guess = guessfield.gettext(); try { int g = Integer.parseInt( guess ); control.playgame( g ); catch( NumberFormatException ex ) { displayplayresult("not a number, try again"); //GEN-LAST:event_guessButtonActionPerformed private void rangebuttonactionperformed(java.awt.event.actionevent evt) {//GEN-FIRST:event_rangeButtonActionPerformed if ( control == null ) return; try { String lowtext = lowfield.gettext(); String hightext = highfield.gettext(); int hi = Integer.parseInt( hightext ); int lo = Integer.parseInt( lowtext ); control.setrange( hi, lo ); catch( NumberFormatException ex ) { displayplayresult("invalid range"); //GEN-LAST:event_rangeButtonActionPerformed /** args the command line arguments */ public static void main(string args[]) { java.awt.eventqueue.invokelater(new Runnable() { public void run() { new HiLoApp().setVisible(true); ); // Variables declaration - do not modify//gen-begin:variables private javax.swing.jlabel frametitle; private javax.swing.jbutton guessbutton; private javax.swing.jtextfield guessfield; private javax.swing.jlabel guesslabel; private javax.swing.jtextfield highfield; private javax.swing.jpanel highform; private javax.swing.jlabel highlabel; private javax.swing.jscrollpane jscrollpane1; private javax.swing.jtextfield lowfield; private javax.swing.jpanel lowform; private javax.swing.jlabel lowlabel; private javax.swing.jpanel playform; private javax.swing.jpanel playinputform; private javax.swing.jlabel playresultfield; private javax.swing.jbutton rangebutton; private javax.swing.jpanel rangeform; private javax.swing.jpanel scoreform; private javax.swing.jtextarea scoretextarea; private javax.swing.jpanel toppanel; // End of variables declaration//gen-end:variables Does this class do one thing, and is it done well? How many other classes does it depend on? HiLo Game Class Diagram (gui) 21 of 22 09/12/ :23 AM
22 GUI and Text Comment on the differences between the two implementations. 22 of 22 09/12/ :23 AM
23 2 Remaining GRASP The remaining 4 GRASP patterns will be covered. Polymorphism - behaviour depends on the type Pure Fabrication - class based in software world Indirection - avoid direct coupling with an intermediary Protected Variations - information hiding - open/close The first five GRASP patterns were: Expert - assign responsibilities to class with knowledge Creator - knows the necessary details to create High Cohesion - does related things Low Coupling - reduce connectivity Controller - use cases or system based classes Polymorphism Name: Polymorphism Problem: How to handle behaviour based on type (i.e., class), but not with an if or switch statement? Polymorphism is also used to create pluggable software components. When alternate behaviors are selected based on the type of an object, use polymorphic method call to select the behavior, rather than use if statements to test the type., Patterns in Java, Vol 2., p 69 Solution: In Java, polymorphism is realized by overriding a method from a super class or implementing an interface. The implemented overridden methods are polymorphic in that a client class uses the same method, but the behaviour depends on the type of the object being referenced. Discussion: The Polymorphism GRASP pattern deals with how a general responsibility gets distributed to a set of classes or interfaces. For example, the responsibility of calculating grades depends on the type of marking scheme for a particular student. If polymorphism is not used, and instead the code tests the type of the object, then that section of code will grow as more types are added to the system. This section of code becomes more coupled (i.e., it knows about more types) and less cohesive (i.e., it is doing too much). A software component is pluggable if it presents itself as the known class or interface. 1 of 20 09/12/ :24 AM
24 2 Responsibilities that can be polymorphic Consider the following. How creatures respond to being attacked in a DandD game. How a connection is made to a WIFI access point. How a ship in the game of Battleship is displayed on screen. How much time a route takes to travel depends on the type of segments in the route. How a wall is detected by a robot depends on the type of sensors used. How a player plays a game a RISK depends of if the player is a human or machine. In each of the above cases, the type of the object being asks results in different behaviour. The polymorphism pattern assigns the responsibility to a subclass or a class the implements a known interface. Anymore examples from the projects? Polymorphism in Java API Polymorphism is used throughout the Java API, consider: The hashcode(), tostring(), getclass(), equals(), and clone() methods of java.lang.object should or must be provided by all Java class (since all Java classes inherit java.lang.object). The drawing and event processing of Swing components is the responsibilities of each distinct Swing component. The Swing package provides many more examples of polymorphism (e.g., javax.swing.plaf.uiresource, javax.swing.border.abstractborder, javax.swing.text.abstractdocument,... ). Similar to the Swing package, the AWT package also has examples of polymorphism. The data structures and algorithms used by the classes that implement java.util.list depend on the implementing class (e.g., array for ArrayList, linked list for LinkedList). The java.util.bag, java.util.set, and java.util.map are interfaces for concrete classes that implement different data structures and algorithms for these interfaces. The java.io.reader, java.io.writer have extended class that specialize the basic IO operations. Other Java examples of polymorphism are: java.util.eventobject, java.util.concurrent.executorservice, javax.imageio.iioparam, java.sql.resultset, java.security.key,... See for class diagrams of the Java api. Polymorphism in java.io Identify the polymorphism is the code that copies files: import java.io.ioexception; import java.io.bufferedreader; import java.io.filereader; import java.io.bufferedwriter; import java.io.filewriter; poly/copyfile.java 2 of 20 09/12/ :24 AM
25 2 public class CopyFile { public static void main( String[] args ) throws IOException { if( args.length!= 2 ) { System.out.println("usage: java CopyFile infile outfile"); System.exit( 1 ); BufferedReader rd = new BufferedReader( new FileReader( args[0] )); BufferedWriter wt = new BufferedWriter( new FileWriter( args[1] )); String line = null; while( (line=rd.readline())!= null ) { wt.write( line ); wt.newline(); rd.close(); wt.close(); Polymorphism with streams The polymorphism is more explicit in this example: import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.io.fileinputstream; import java.io.bufferedinputstream; import java.io.bufferedoutputstream; import java.io.fileoutputstream; poly/copyfilestream.java public class CopyFileStream { public static void main( String[] args ) throws IOException { if( args.length!= 2 ) { System.out.println("usage: java CopyFileStream infile outfile"); System.exit( 1 ); InputStream ins = new BufferedInputStream( new FileInputStream( args[0] )); OutputStream os = new BufferedOutputStream( new FileOutputStream( args[1] )); byte[] buf = new byte[2048]; int amt; while( (amt=ins.read( buf )) > 0 ) { os.write( buf, 0, amt ); ins.close(); os.close(); Polymorphism example (interface) 3 of 20 09/12/ :24 AM
26 2 A possible set of two dimensional shapes include: circle, triangle, and square. Each of these shapes has an area and a perimeter. The calculation of area and perimeter depend on the type of shape. A possible shape interface is: public interface Shape2D { public double area(); public double perimeter(); shapes/shape2d.java Class implementations for circle, triangle, and square are: import static java.lang.math.pi; shapes/circle.java public class Circle implements Shape2D { private double radius; public Circle( double radius ) { this.radius = radius; public double area() { return PI * radius * radius; public double perimeter() { return PI * 2 * radius; import static java.lang.math.sqrt; shapes/triangle.java public class Triangle implements Shape2D { private double a, b, c; public Triangle( double a, double b, double c ) { this.a = a; this.b = b; this.c = c; public double area() { // Heron's formula return sqrt( (a+b-c)*(a-b+c)*(-a+b+c)*(a+b+c) ) / 4.0; public double perimeter() { return a+b+c; 4 of 20 09/12/ :24 AM
27 2 public class Square implements Shape2D { private double side; shapes/square.java public Square( double side ) { this.side = side; public double area() { return side * side; public double perimeter() { return 4 * side; The Information Expert pattern suggests that the area and perimeter calculations belong to each class, since the information need to calculate the area is present in each class. Given a shape, code that print its area is: Shape s = // a Triangle, Circle, or Square object System.out.println( s.area() ); Without polymorphism, the code would be: Shape s = // Triangle, Circle, or Square if ( s instanceof Triangle ) { Triangle t = (Triangle)s; System.out.println( t.area() ); else if ( s instanceof Circle ) { Circle c = (Triangle)c; System.out.println( c.area() ); else if ( s instanceof Square ) { Square sq = (Square)s; System.out.println( sq.area() ); Of course without polymorphism, interfaces would not make any sense. The second code fragment is not as cohesive as the first. It also has more coupling, since it knows about Triangle, Circle, and Square. Additionally, any new shapes require the modification of the above code. Polymorphism example (abstract class) Inheriting from a class can also be used to realize the polymorphism of the perimeter and 5 of 20 09/12/ :24 AM
28 2 area responsibilities. The class is abstract, since there are no meaningfully definition of area and perimeter without a real shape. import static java.lang.math.sqrt; import static java.lang.math.pi; shapes/abstractshape.java public abstract class AbstractShape { public abstract double area(); public abstract double perimeter(); class Triangle extends AbstractShape { private double a, b, c; public Triangle( double a, double b, double c ) { this.a = a; this.b = b; this.c = c; public double area() { // Heron's formula return sqrt( (a+b-c)*(a-b+c)*(-a+b+c)*(a+b+c) ) / 4.0; public double perimeter() { return a+b+c; class Square extends AbstractShape { private double side; public Square( double side ) { this.side = side; public double area() { return side * side; public double perimeter() { return 4 * side; class Circle extends AbstractShape { private double radius; public Circle( double radius ) { this.radius = radius; 6 of 20 09/12/ :24 AM
29 2 public double area() { return PI * radius * radius; public double perimeter() { return PI * 2 * radius; Larman suggest that interfaces should be used..., when you want to support polymorphism without being committed to a particular class hierarchy. Interfaces are also required when more then one set of methods must be polymorphic (i.e., multiple inheritance is required). Expression Polymorphism The expression, 3.0 * , can represented by an abstract syntax tree. + * Every element in the tree can be evaluated. A class that represents any expression is: public abstract class Expr { public abstract double evaluate(); AST/Expr.java The polymorphism pattern suggest that every distinct expression object should override the evaluate method. Constant, plus, and times expression can be implemented with: public class ConstantExpr extends Expr { private double value; AST/ConstantExpr.java public double evaluate() { return value; public ConstantExpr( double value ) { this.value = value; AST/PlusExpr.java 7 of 20 09/12/ :24 AM
30 2 public class PlusExpr extends Expr { private Expr left, right; public double evaluate() { return left.evaluate() + right.evaluate(); public PlusExpr( Expr left, Expr right ) { this.left = left; this.right = right; public class TimesExpr extends Expr { private Expr left, right; AST/TimesExpr.java public double evaluate() { return left.evaluate() * right.evaluate(); public TimesExpr( Expr left, Expr right ) { this.left = left; this.right = right; How would a subtraction expression be supported? Testing Expr import org.junit.*; import static org.junit.assert.*; AST/ExprTesting.java /* * javac -cp junit-4.7.jar:. ExprTesting.java * java -cp junit-4.7.jar:. org.junit.runner.junitcore ExprTesting */ public class ExprTesting { private static final Expr one = new ConstantExpr( 1.0 ); private static final Expr negone = new ConstantExpr( -1.0 ); private static final Expr two = new ConstantExpr( 2.0 ); private static final double EPSILON = public void singleexpressions() { // expr: 1.0 asserttrue( one.evaluate() == 1.0 ); // expr: -1.0 asserttrue( negone.evaluate() == -1.0 ); // expr: 2.0 asserttrue( two.evaluate() == 2.0 ); 8 of 20 09/12/ :24 AM
31 public void compoundexpressions() { // expr: PlusExpr pe = new PlusExpr( one, two ); assertequals( pe.evaluate(), 3.0, EPSILON ); // expr: 1.0 * 2.0 TimesExpr te = new TimesExpr( one, two ); assertequals( te.evaluate(), 2.0, EPSILON ); // expr: -1.0 * ( ) TimesExpr e1 = new TimesExpr( negone, pe ); assertequals( e1.evaluate(), -3.0, EPSILON ); // expr: (1.0 * 2.0) * ( ) TimesExpr e2 = new TimesExpr( te, pe ); assertequals( e2.evaluate(), 6.0, EPSILON ); Nonpolymophic Expression Implementation An implementation of a nonpolymophic expression evaluator is: public class NonPolyExpr { public static final int CONST_EXPR = 1; public static final int PLUS_EXPR = 2; public static final int TIMES_EXPR = 3; AST/NonPolyExpr.java private int type; private double value; private NonPolyExpr left=null, right=null; public NonPolyExpr( int type, double value ) { this.type = type; this.value = value; public NonPolyExpr( int type, NonPolyExpr left, NonPolyExpr right) { this.type = type; this.left = left; this.right = right; public double evaluate() { switch( type ) { case CONST_EXPR: return value; case PLUS_EXPR: return left.evaluate() + right.evaluate(); case TIMES_EXPR: return left.evaluate() * right.evaluate(); return java.lang.double.nan; // what is this? 9 of 20 09/12/ :24 AM
32 2 The nonpolymophic implementation suffers from the following design problems: The NonPolyExpr.evaluate method is not as cohesive as the polymorphic versions, since the NonPolyExpr class must handle all the cases, while the polymorphic class only deal with one operation. The NonPolyExpr cannot be easily extended, while the polymorphic version is extended by adding new class the extends Expr. This new expression operation can then be used by all other classes. Using NonPolyExpr.evaluate, requires knowledge of the expression types, and therefore is more coupled to the client classes. What is the result of: // a, b are NonPolyExpr objects NonPolyExpr e = new NonPolyExpr(NonPolyExpr.CONST_EXPR,a,b); System.out.print( e.evaluate() ); An implementation of polymorphism in C The following C-language program demonstrates the essentials of how polymorphism is implemented. In addition to the data parts of an object, the object contains a table of method pointers for each overridden method. The table is consulted to invoke the correct method. #include <stdio.h> c-poly/poly_in_c.c typedef void (*func_v_vp_ptr)(void *); typedef struct { int value; // data part func_v_vp_ptr print; // virtual method base_class; void base_print(void *p) { base_class *self = (base_class *)p; printf("base %d\n", self->value ); void base_init( base_class *self, int value) { self->value = value; self->print = base_print; void invoke_print( base_class *self ) { (*self->print)(self); 10 of 20 09/12/ :24 AM
33 2 void derived_print(void *p) { base_class *self = (base_class *)p; printf("derived %d\n", self->value ); void derived_init( base_class *self, int value) { self->value = value; self->print = derived_print; int main( int ac, char *av[] ) { base_class b1, d1; base_init( &b1, 1); derived_init( &d1, 2); invoke_print( &b1 ); invoke_print( &d1 ); Hopeful, this demonstrates why learning C is good for you (or perhaps not!). Pure Fabrication Name: Pure Fabrication Problem: What object should have the responsibility, when you do not want to violate High Cohesion and Low Coupling, or other goals, but solutions offered by Expert are not appropriate., Larman, p 421. You must assign a responsibility to a class, but assigning it to a class that represents a conceptual model entity would ruin its low coupling or high cohesion. You resolve this problem by fabricating a class that does not represent an entity in your conceptual model., Patterns in Java, Vol. 2, p 73. In other words, not all responsibilities can be assigned to domain classes, especially responsibilities that deal with implementation technologies (i.e., persistence storage, network communication,...). Solution: Assign a highly cohesive set of responsibilities to an artificial or convenience class that does 11 of 20 09/12/ :24 AM
/** Creates new form NewJFrame */ public NewJFrame() { initcomponents(); initblogsearch(); //initializes Index List box }
/* * To change this template, choose Tools Templates * and open the template in the editor. */ /* * NewJFrame.java * * Created on Apr 17, 2011, 1:13:13 PM */ /** * * @author Kelli */ import java.io.*;
More informationI pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.
Name: Covers Chapters 1-3 50 mins CSCI 1301 Introduction to Programming Armstrong Atlantic State University Instructor: Dr. Y. Daniel Liang I pledge by honor that I will not discuss this exam with anyone
More informationObject-Oriented Design
Object-Oriented Design Lecturer: Raman Ramsin Lecture 15: Object-Oriented Principles 1 Open Closed Principle (OCP) Classes should be open for extension but closed for modification. OCP states that we should
More informationAnswer on question #61311, Programming & Computer Science / Java
Answer on question #61311, Programming & Computer Science / Java JSP JSF for completion Once the user starts the thread by clicking a button, the program must choose a random image out of an image array,
More informationCore Java Contents. Duration: 25 Hours (1 Month)
Duration: 25 Hours (1 Month) Core Java Contents Java Introduction Java Versions Java Features Downloading and Installing Java Setup Java Environment Developing a Java Application at command prompt Java
More informationObject-Oriented Design
Object-Oriented Design Department of Computer Engineering Lecture 12: Object-Oriented Principles Sharif University of Technology 1 Open Closed Principle (OCP) Classes should be open for extension but closed
More information* To change this license header, choose License Headers in Project Properties.
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools Templates * and open the template in the editor. */ package calci; /** * *
More informationCN208 Introduction to Computer Programming
CN208 Introduction to Computer Programming Lecture #11 Streams (Continued) Pimarn Apipattanamontre Email: pimarn@pimarn.com 1 The Object Class The Object class is the direct or indirect superclass of every
More informationPIC 20A Streams and I/O
PIC 20A Streams and I/O Ernest Ryu UCLA Mathematics Last edited: December 7, 2017 Why streams? Often, you want to do I/O without paying attention to where you are reading from or writing to. You can read
More informationFull file at
Chapter 1 Primitive Java Weiss 4 th Edition Solutions to Exercises (US Version) 1.1 Key Concepts and How To Teach Them This chapter introduces primitive features of Java found in all languages such as
More informationTirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax
Tirgul 1 Today s topics: Course s details and guidelines. Java reminders and additions: Packages Inner classes Command Line rguments Primitive and Reference Data Types Guidelines and overview of exercise
More informationPage 1 of 16. Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.
Page 1 of 16 HAND IN Answers Are Recorded on Question Paper QUEEN'S UNIVERSITY SCHOOL OF COMPUTING CISC212, FALL TERM, 2005 FINAL EXAMINATION 9am to 12noon, 19 DECEMBER 2005 Instructor: Alan McLeod If
More informationFinal Exam. Final Exam Review. Ch 1: Introduction: Object-oriented analysis, design, implementation. Exam Format
Final Exam Final Exam Review CS 4354 Fall 2012 Jill Seaman Friday, December 14, 11AM Closed book, closed notes, clean desk Content: Textbook: Chapters 1, 2, 4-10 Java Lectures, GRASP + JUnit 35% of your
More informationLast Time: Object Design. Comp435 Object-Oriented Design. Last Time: Responsibilities. Last Time: Creator. Last Time: The 9 GRASP Patterns
Last Time: Object Design Comp435 Object-Oriented Design Week 7 Computer Science PSU HBG The main idea RDD: Responsibility-Driven Design Identify responsibilities Assign them to classes and objects Responsibilities
More informationINSTITUTO POLITÉCNICO NACIONAL ESCUELA SUPERIOR DE CÓMPUTO
INSTITUTO POLITÉCNICO NACIONAL ESCUELA SUPERIOR DE CÓMPUTO Cryptography Practice 1,2,3 By: Raúl Emmanuel Delgado Díaz de León Professor: M. en C. NIDIA ASUNCIÓN CORTEZ DUARTE February2015 Index Contenido
More informationCS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE
CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate
More informationUNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED
UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED EXERCISE 11.1 1. static public final int DEFAULT_NUM_SCORES = 3; 2. Java allocates a separate set of memory cells in each instance
More informationCH. 2 OBJECT-ORIENTED PROGRAMMING
CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED
More informationJava Programming Summer 2008 LAB. Thursday 8/21/2008
LAB Thursday 8/21/2008 Design and implement the program that contains a timer. When the program starts, the timer shows 00:00:00. When we click the Start button, the timer starts. When we click the Stop
More information* To change this license header, choose License Headers in Project Properties.
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools Templates * and open the template in the editor. package tugasumbyjava; /**
More informationCSE 70 Final Exam Fall 2009
Signature cs70f Name Student ID CSE 70 Final Exam Fall 2009 Page 1 (10 points) Page 2 (16 points) Page 3 (22 points) Page 4 (13 points) Page 5 (15 points) Page 6 (20 points) Page 7 (9 points) Page 8 (15
More informationUse the scantron sheet to enter the answer to questions (pages 1-6)
Use the scantron sheet to enter the answer to questions 1-100 (pages 1-6) Part I. Mark A for True, B for false. (1 point each) 1. Abstraction allow us to specify an object regardless of how the object
More informationCourse overview: Introduction to programming concepts
Course overview: Introduction to programming concepts What is a program? The Java programming language First steps in programming Program statements and data Designing programs. This part will give an
More informationChapter 11 Classes Continued
Chapter 11 Classes Continued The real power of object-oriented programming comes from its capacity to reduce code and to distribute responsibilities for such things as error handling in a software system.
More informationWOSO Source Code (Java)
WOSO 2017 - Source Code (Java) Q 1 - Which of the following is false about String? A. String is immutable. B. String can be created using new operator. C. String is a primary data type. D. None of the
More informationJAVA. Duration: 2 Months
JAVA Introduction to JAVA History of Java Working of Java Features of Java Download and install JDK JDK tools- javac, java, appletviewer Set path and how to run Java Program in Command Prompt JVM Byte
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationPrelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer
Prelim 1 SOLUTION CS 2110, September 29, 2016, 7:30 PM 0 1 2 3 4 5 Total Question Name Loop invariants Recursion OO Short answer Exception handling Max 1 15 15 25 34 10 100 Score Grader 0. Name (1 point)
More informationFull file at Chapter 2 - Inheritance and Exception Handling
Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a
More informationGive one example where you might wish to use a three dimensional array
CS 110: INTRODUCTION TO COMPUTER SCIENCE SAMPLE TEST 3 TIME ALLOWED: 60 MINUTES Student s Name: MAXIMUM MARK 100 NOTE: Unless otherwise stated, the questions are with reference to the Java Programming
More informationpublic static boolean isoutside(int min, int max, int value)
See the 2 APIs attached at the end of this worksheet. 1. Methods: Javadoc Complete the Javadoc comments for the following two methods from the API: (a) / @param @param @param @return @pre. / public static
More informationText User Interfaces. Keyboard IO plus
Text User Interfaces Keyboard IO plus User Interface and Model Model: objects that solve problem at hand. User interface: interacts with user getting input from user giving output to user reporting on
More informationPage 1 of 16. Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.
Page 1 of 16 SOLUTION HAND IN Answers Are Recorded on Question Paper QUEEN'S UNIVERSITY SCHOOL OF COMPUTING CISC212, FALL TERM, 2005 FINAL EXAMINATION 9am to 12noon, 19 DECEMBER 2005 Instructor: Alan McLeod
More informationSimple Data Source Crawler Plugin to Set the Document Title
Simple Data Source Crawler Plugin to Set the Document Title IBM Content Analytics 1 Contents Introduction... 4 Basic FS Crawler behavior.... 8 Using the Customizer Filter to Modify the title Field... 13
More informationLampiran A. SOURCE CODE PROGRAM
A-1 Lampiran A. SOURCE CODE PROGRAM Frame Utama package FrameDesign; import ArithmeticSkripsi.ArithmeticCompress; import ArithmeticSkripsi.ArithmeticDecompress; import Deflate.DeflateContoh; import java.io.file;
More informationCS 251 Intermediate Programming Java I/O Streams
CS 251 Intermediate Programming Java I/O Streams Brooke Chenoweth University of New Mexico Spring 2018 Basic Input/Output I/O Streams mostly in java.io package File I/O mostly in java.nio.file package
More informationComplete Java Contents
Complete Java Contents Duration: 60 Hours (2.5 Months) Core Java (Duration: 25 Hours (1 Month)) Java Introduction Java Versions Java Features Downloading and Installing Java Setup Java Environment Developing
More informationグラフを表すデータ構造 JAVA での実装
グラフを表すデータ構造 JAVA での実装 グラフの構造を記述するクラス パッケージgraphLib graphlib.graph グラフ全体 graphlib.vertex 頂点 頂点を始点とする弧 頂点を2 次元面に表示するための座標 graphlib.arc 弧の始点と終点 クラスの関係 グラフ 弧一覧 弧 弧 頂点 弧 頂点一覧 頂点 頂点 写像 + 頂点 写像 頂点 写像 δ + GRAPH
More informationGRASP Design Patterns A.A. 2018/2019
GRASP Design Patterns A.A. 2018/2019 Objectives Introducing design patterns Introduzione ai design pattern Designing objects and responsibilities GRASP design patterns A long corridor A passage room Does
More informationF1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept
F1 A Java program Ch 1 in PPIJ Introduction to the course The computer and its workings The algorithm concept The structure of a Java program Classes and methods Variables Program statements Comments Naming
More informationOutline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.
Outline Inheritance Class Extension Overriding Methods Inheritance and Constructors Polymorphism Abstract Classes Interfaces 1 OOP Principles Encapsulation Methods and data are combined in classes Not
More informationChapter 10 Classes Continued. Fundamentals of Java
Chapter 10 Classes Continued Objectives Know when it is appropriate to include class (static) variables and methods in a class. Understand the role of Java interfaces in a software system and define an
More informationObject-Oriented Design I - SOLID
Object-Oriented Design I - SOLID SWEN-261 Introduction to Software Engineering Department of Software Engineering Rochester Institute of Technology Single responsibility Open/close Liskov substitution
More informationCS Programming I: File Input / Output
CS 200 - Programming I: File Input / Output Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624
More informationOBJECT ORİENTATİON ENCAPSULATİON
OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual
More informationBasic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems
Basics of OO Programming with Java/C# Basic Principles of OO Abstraction Encapsulation Modularity Breaking up something into smaller, more manageable pieces Hierarchy Refining through levels of abstraction
More informationI/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O
I/O 10-7-2013 I/O in Java I/O streams vs. Reader/Writer HW#3 due today Reading Assignment: Java tutorial on Basic I/O public class Swimmer implements Cloneable { public Date geteventdate() { return (Date)
More informationHST 952. Computing for Biomedical Scientists Lecture 8
Harvard-MIT Division of Health Sciences and Technology HST.952: Computing for Biomedical Scientists HST 952 Computing for Biomedical Scientists Lecture 8 Outline Vectors Streams, Input, and Output in Java
More informationGraphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java
More informationEach command-line argument is placed in the args array that is passed to the static main method as below :
1. Command-Line Arguments Any Java technology application can use command-line arguments. These string arguments are placed on the command line to launch the Java interpreter after the class name: public
More informationLanguage Features. 1. The primitive types int, double, and boolean are part of the AP
Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are
More informationProgrammierpraktikum
Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 21 05/07/2012 10:31 AM Input / Output Streams 2 of 21 05/07/2012 10:31 AM Java I/O streams
More informationFirst Name: AITI 2004: Exam 2 July 19, 2004
First Name: AITI 2004: Exam 2 July 19, 2004 Last Name: JSP Track Read Instructions Carefully! This is a 3 hour closed book exam. No calculators are allowed. Please write clearly if we cannot understand
More informationObject-Oriented Design II - GRASP
Object-Oriented Design II - GRASP SWEN-610 Foundations of Software Engineering Department of Software Engineering Rochester Institute of Technology Controller Creator Indirection Information expert High
More informationCSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name
CSC 1051 Algorithms and Data Structures I Final Examination May 12, 2017 Name Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the spaces provided.
More informationThis Week s Agenda (Part A) CS121: Computer Programming I. The Games People Play. Data Types & Structures. The Array in Java.
CS121: Computer Programming I A) Collections B) File I/O & Error Handling Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use
More informationLecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting
Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006
More informationF I N A L E X A M I N A T I O N
Faculty Of Computer Studies M257 Putting Java to Work F I N A L E X A M I N A T I O N Number of Exam Pages: (including this cover sheet( Spring 2011 April 4, 2011 ( 5 ) Time Allowed: ( 1.5 ) Hours Student
More informationDepartment of Civil and Environmental Engineering, Spring Semester, ENCE 688R: Midterm Exam: 1 1/2 Hours, Open Book and Open Notes
Department of Civil and Environmental Engineering, Spring Semester, 2013 ENCE 688R: Midterm Exam: 1 1/2 Hours, Open Book and Open Notes Name : Question Points Score 1 30 2 30 3 40 Total 100 1 Question
More informationHighlights of Last Week
Highlights of Last Week Refactoring classes to reduce coupling Passing Object references to reduce exposure of implementation Exception handling Defining/Using application specific Exception types 1 Sample
More informationInheritance (Part 5) Odds and ends
Inheritance (Part 5) Odds and ends 1 Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there
More informationOutline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring
Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,
More informationCOMP 110 Programming Exercise: Simulation of the Game of Craps
COMP 110 Programming Exercise: Simulation of the Game of Craps Craps is a game of chance played by rolling two dice for a series of rolls and placing bets on the outcomes. The background on probability,
More informationExceptions and Working with Files
Exceptions and Working with Files Creating your own Exceptions. You have a Party class that creates parties. It contains two fields, the name of the host and the number of guests. But you don t want to
More informationVirtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.
1 - What if the main method is declared as private? 1. The program does not compile 2. The program compiles but does not run 3. The program compiles and runs properly ( From Lectuer # 2) 4. The program
More informationWA1278 Introduction to Java Using Eclipse
Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA1278 Introduction to Java Using Eclipse This course introduces the Java
More informationProgramming Assignment #1 (Java)
Programming Assignment #1 (Java) CS 671 due 9 Feb 2014 11:59pm 1. Implement the class HiLo. 20 pts 2. Implement the class Liar. 50 pts 3. Complete the class GuesserTextUI. 30 pts The objective of this
More informationCS Programming I: File Input / Output
CS 200 - Programming I: File Input / Output Marc Renault Department of Computer Sciences University of Wisconsin Madison Spring 2018 TopHat Sec 3 (AM) Join Code: 427811 TopHat Sec 4 (PM) Join Code: 165455
More informationAbstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.
a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract
More informationFull download all chapters instantly please go to Solutions Manual, Test Bank site: testbanklive.com
Introduction to Java Programming Comprehensive Version 10th Edition Liang Test Bank Full Download: http://testbanklive.com/download/introduction-to-java-programming-comprehensive-version-10th-edition-liang-tes
More informationChapter 10. IO Streams
Chapter 10 IO Streams Java I/O The Basics Java I/O is based around the concept of a stream Ordered sequence of information (bytes) coming from a source, or going to a sink Simplest stream reads/writes
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Interface Abstract data types Version of January 26, 2013 Abstract These lecture notes are meant
More informationCOMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output
COMP 213 Advanced Object-oriented Programming Lecture 19 Input/Output Input and Output A program that read no input and produced no output would be a very uninteresting and useless thing. Forms of input/output
More informationHanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS
Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS Glossary of Terms 2-4 Step by Step Instructions 4-7 HWApp 8 HWFrame 9 Never trust a computer
More informationClasses Basic Overview
Final Review!!! Classes and Objects Program Statements (Arithmetic Operations) Program Flow String In-depth java.io (Input/Output) java.util (Utilities) Exceptions Classes Basic Overview A class is a container
More informationCS 520 Theory and Practice of Software Engineering Fall 2018
Today CS 520 Theory and Practice of Software Engineering Fall 2018 Object Oriented (OO) Design Principles September 13, 2018 Code review and (re)design of an MVC application (and encapsulation) Polymorphism
More informationFile IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20
File IO Computer Science and Engineering College of Engineering The Ohio State University Lecture 20 I/O Package Overview Package java.io Core concept: streams Ordered sequences of data that have a source
More informationChapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.
Chapter 10 File I/O Copyright 2016 Pearson Inc. All rights reserved. Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program,
More informationSpecial error return Constructors do not have a return value What if method uses the full range of the return type?
23 Error Handling Exit program (System.exit()) usually a bad idea Output an error message does not help to recover from the error Special error return Constructors do not have a return value What if method
More informationProject #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.
Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple magazine data system. Milestones:
More informationCS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle
Boggle If you are not familiar with the game Boggle, the game is played with 16 dice that have letters on all faces. The dice are randomly deposited into a four-by-four grid so that the players see the
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract
More informationBasic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)
I/O and Scannar Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 I/O operations Three steps:
More informationM257 Past Paper Oct 2008 Attempted Solution
M257 Past Paper Oct 2008 Attempted Solution Part 1 Question 1 A version of Java is a particular release of the language, which may be succeeded by subsequent updated versions at a later time. Some examples
More informationJava Input/Output. 11 April 2013 OSU CSE 1
Java Input/Output 11 April 2013 OSU CSE 1 Overview The Java I/O (Input/Output) package java.io contains a group of interfaces and classes similar to the OSU CSE components SimpleReader and SimpleWriter
More informationChapter 6 Introduction to Defining Classes
Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of
More informationCSCI 200 Lab 2 Inheritance, Polymorphism & Data Streams
CSCI 200 Lab 2 Inheritance, Polymorphism & Data Streams In this lab you will write a set of simple Java interfaces and classes that use inheritance and polymorphism. You will also write code that uses
More informationCO Java SE 8: Fundamentals
CO-83527 Java SE 8: Fundamentals Summary Duration 5 Days Audience Application Developer, Developer, Project Manager, Systems Administrator, Technical Administrator, Technical Consultant and Web Administrator
More informationCSC 1214: Object-Oriented Programming
CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: www: materials: e-learning environment: office: alt. office: jkizito@cis.mak.ac.ug http://serval.ug/~jona http://serval.ug/~jona/materials/csc1214
More informationProctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.
HAND IN Answers Are Recorded on Question Paper QUEEN'S UNIVERSITY SCHOOL OF COMPUTING CISC212, FALL TERM, 2006 FINAL EXAMINATION 7pm to 10pm, 19 DECEMBER 2006, Jeffrey Hall 1 st Floor Instructor: Alan
More informationCS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide
CS1092: Tutorial Sheet: No 3 Exceptions and Files Tutor s Guide Preliminary This tutorial sheet requires that you ve read Chapter 15 on Exceptions (CS1081 lectured material), and followed the recent CS1092
More informationS.No Question Blooms Level Course Outcome UNIT I. Programming Language Syntax and semantics
S.No Question Blooms Level Course Outcome UNIT I. Programming Language Syntax and semantics 1 What do you mean by axiomatic Knowledge C254.1 semantics? Give the weakest precondition for a sequence of statements.
More informationContents. iii Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services August 1998, Revision B
Contents About the Course...xv Course Overview... xvi Course Map... xvii Module-by-Module Overview... xviii Course Objectives... xxii Skills Gained by Module... xxiii Guidelines for Module Pacing... xxiv
More information1.00 Lecture 30. Sending information to a Java program
1.00 Lecture 30 Input/Output Introduction to Streams Reading for next time: Big Java 15.5-15.7 Sending information to a Java program So far: use a GUI limited to specific interaction with user sometimes
More informationCISC 323 (Week 9) Design of a Weather Program & Java File I/O
CISC 323 (Week 9) Design of a Weather Program & Java File I/O Jeremy Bradbury Teaching Assistant March 8 & 10, 2004 bradbury@cs.queensu.ca Programming Project The next three assignments form a programming
More informationThe Sun s Java Certification and its Possible Role in the Joint Teaching Material
The Sun s Java Certification and its Possible Role in the Joint Teaching Material Nataša Ibrajter Faculty of Science Department of Mathematics and Informatics Novi Sad 1 Contents Kinds of Sun Certified
More informationpackage As7BattleShip;
package As7BattleShip; Program: BattleshipBoard.java Author: Kevin Nider Date: 11/18/12 Description: Assignment 7: Runs the battleship game Input: ship placement board files and computer player type Output:
More informationJava and OOP. Part 5 More
Java and OOP Part 5 More 1 More OOP More OOP concepts beyond the introduction: constants this clone and equals inheritance exceptions reflection interfaces 2 Constants final is used for classes which cannot
More informationChapter 2. Network Chat
Chapter 2. Network Chat In a multi-player game, different players interact with each other. One way of implementing this is to have a centralized server that interacts with each client using a separate
More information