Modularity - PowerPoint PPT Presentation

1 / 20
About This Presentation
Title:

Modularity

Description:

length() the number of characters. toUpperCase(), toLowerCase(), trim ... here: deep copy up to (data.length 1) data = newData; // copy reference (discard ... – PowerPoint PPT presentation

Number of Views:62
Avg rating:3.0/5.0
Slides: 21
Provided by: michaelc7
Category:

less

Transcript and Presenter's Notes

Title: Modularity


1
Modularity
  • Also a structured programming topic
  • Can replace a rectangle with a module
  • Modules contain stacked/nested structures
  • Java modules
  • methods (the most basic modular units)
  • classes (collections of related methods)
  • packages (collections of related classes)

2
Using methods invoking
  • Direct translation of algorithm e.g.,
  • getData()
  • process()
  • showResults()
  • In turn, the method process() might do
  • result calculate(x, y)
  • where calculate is another method, one that
    returns a value based on x and y.
  • And so on

3
static methods and variables
  • A.k.a. class methods and class variables
  • Technically, same for all instances of a class
  • No particular instance (object) is involved
  • So instance variables have no meaning in a static
    context
  • Access by class name, not object reference
  • Good for self-contained methods
  • i.e., all necessary info is local to the method
  • May not use non-static methods or variables of
    class
  • Good for shared data and instance counts
  • e.g., if (Martian.count gt 10) retreat()

4
java.lang.Math static methods
  • Maths public methods are all static
  • So no need to make an object first
  • Invoke by class name and the dot . operator
  • Math.max(x, y) and Math.min(x, y)
  • max and min are overloaded return type same as
    x, y
  • Usually double parameters and return type
  • double r Math.toRadians(57.)
  • System.out.println(Sine of 57 degrees is
  • Math.sin(r))
  • Also two constant values Math.PI and Math.E
  • Math is in java.lang so no need to import

5
About constants like PI and E
  • final variables are constants
  • May only assign value once usually when declared
  • More efficient code (and often programming)
  • Should always avoid magic numbers
  • e.g., decipher this line of code
  • cost price 1.0775 4.5
  • More typing, but worth it
  • final double TAX_RATE 0.0775
  • final double SHIPPING 4.5
  • cost price (1. TAX_RATE) SHIPPING
  • Class constants final static variables
  • e.g., Math.PI is declared in java.lang.Math as
    follows
  • public static final double PI
    3.14159265358979323846

6
Some String methods
  • Accessing sub-strings (Note positions start
    at 0, not 1)
  • substring(int) returns end of string
  • substring(int, int) returns string from first
    position to just before last position
  • charAt(int) returns single char
  • length() the number of characters
  • toUpperCase(), toLowerCase(), trim(),
  • valueOf() converts any type to a String
  • But converting from a String more difficult
    must use specialized methods to parse

7
Note parameters are copies
  • e.g., void foo(int x)
  • x 5 // changes copy of the value
    passed
  • So what does the following code print?
  • int a 1
  • foo(a)
  • System.out.print(a a)
  • Answer a 1
  • Same applies to immutable objects like Strings
  • String s APPLE
  • anyMethod(s)
  • System.out.print(s) // prints APPLE

8
But references are references
  • A reference is used to send messages to an object
  • So the original object can change if not
    immutable
  • e.g., void foo(Rectangle x)
  • x.translate(5,5)
  • // actually moves the rectangle
  • Copy of reference is just as useful as the
    original
  • i.e., although methods cannot change a reference,
    they can change the original object
  • Moral be careful about passing object references

9
Random simulations
  • Can use Math.random() method
  • Pseudorandom double value range 0 to almost 1
  • int diceValue 1 (int)(Math.random() 6)
  • Better to use a java.util.Random object
  • Random generator new Random()
  • int diceValue 1 generator.nextInt(6)
  • e.g., RandomIntegers.java (Fig. 6.7, p. 221)
  • And more interesting Craps.java (Fig. 6.9, pp.
    225-226)
  • Not just for integers (and not just for dice)
  • double angle 360 generator.nextDouble()
  • boolean gotLucky generator.nextBoolean()

10
Scope/duration of identifiers
  • Depends on where declared
  • i.e., in which set of in which block
  • Instance variables
  • Duration (lifetime) same as duration of object
  • Scope available throughout the class
  • Variables declared in method or other block
    (including formal parameters)
  • Duration as long as block is being executed
  • Scope available just within the block
  • See Scope.java (Fig. 6.11, p. 230)

11
Overloading method names
  • Method signature is name (parameter list)
  • Can reuse a name with different parameter list
  • List distinguished by (1) number of parameters,
    and (2) types and order of parameters
  • e.g., three greeting methods (for a robot?)
  • void hi() System.out.print(Hi)
  • void hi(String name) // to greet a person by name
  • System.out.print(Hi name)
  • void hi(int number) // to greet a collection of
    people
  • System.out.print(Hi you number)
  • Another example MethodOverload.java (Fig. 6.13,
    p. 233)
  • Cannot distinguish just by return type though
    (Fig. 6.15)

12
Another aside Coloring and animating drawings
  • e.g., DrawSmiley.java (Fig. 6.16, p. 236)
  • Now lets spice up the Car drawing
  • First add a Color instance variable to class Car,
    and add ways to change a Cars position
  • Animation is class CarComponents responsibility
  • Change the two Car references to instance
    variables
  • Create Car objects the first time paintComponent
    is called might as well make their colors
    random
  • Add animate() method moves Cars, and uses a
    Thread
  • try Thread.sleep(500)
  • catch(InterruptedException e)
  • And includes repeated calls to repaint() after
    moves
  • Finally, must invoke animate() from class
    CarViewer

13
What is an array?
  • General answer a fixed number of consecutive
    memory locations, all of the same type.
  • Can refer to all as a group by arrays name
  • Can refer to any one by nameposition
  • Position is called array subscript or index
  • First position is 0 (others are offset from 0)
  • Additional Java answer an object whose purpose
    is to store collections of items of the same type
  • Either primitive data values of the same type
  • Or references to any one class of objects

14
Arrays are objects in Java
  • Even a public instance variable length
  • Range of positions 0 ... length-1
  • Length is fixed after created (instantiated)
  • Declare, instantiate separate steps
  • int x // declare array of int named x
  • int x // same thing (clear that x is an int
    array)
  • x new int4 // instantiate array of length 4
  • Both steps can be done with one statement
  • int x new int4
  • Assign values in a later step
  • x0 53 // first element set to 53

15
Accessing array elements
  • First, another way to instantiate
  • And initialize at the same time
  • int x 3, 7, 4, 5
  • Quiz - what is
  • x0 ?
  • x1-x0 ?
  • xx0 ?
  • x4 ?

3
4
5
throws ArrayIndexOutOfBoundsException
16
Using arrays
  • for loops are especially useful
  • for (int i0 i lt x.length i)
  • xigetValue() // access each xi in order
  • Copying can be deep or shallow
  • Shallow copy a new reference to same array
  • int a x // if x is an int array already
  • Deep copy a new array with copies of all values
  • int a new intx.length // same length as x
  • for (int i0 i lt x.length i)
  • ai xi
  • Using arrays to count RollDie.java (Fig. 7.7, p.
    262)

17
Enhanced for loop Java 5
  • Actually a for each loop
  • for (int element array)
  • Reads for each element in array
  • e.g., array of strings String words
  • for (String s words)
  • System.out.println(s)
  • Note the loop control variable is the array
    element itself, not its array index
  • So not applicable if index value is required
  • Like deep copy algorithm, others

18
Some basic array operations
  • Summing array elements
  • int sum 0 // initialize before loop starts
  • for (int item x) // for each integer item in
    array
  • sum item
  • Finding a maximum (or other extreme)
  • int max x0 // initialize to first value
  • for (int i1 i lt x.length i)
  • if (xi gt max) max xi
  • Printing on one row of standard output
  • for (int item x) System.out.print( item)
  • System.out.println() // newline after row is
    done
  • Q How to print in reverse?

19
  • Maybe more
  • Maybe less

20
Handling array size limitations
  • Issue array size is fixed after construction
  • Dont always know what size to allocate at start
  • Solutions (besides class ArrayList coming soon)
  • Allocate way more than enough
  • Absolutely limits the size of the problem not a
    good idea
  • Create new, larger array, and copy values
  • if (dataSize gt data.length)
  • int newData new int2 data.length
  • ... // here deep copy up to (data.length
    1)
  • data newData // copy reference (discard
    old array)
Write a Comment
User Comments (0)
About PowerShow.com