Method Abstraction Java Programming. Key to developing software is to apply the concept of...

28
Method Abstraction Java Programming
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    220
  • download

    0

Transcript of Method Abstraction Java Programming. Key to developing software is to apply the concept of...

Page 1: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

Method Abstraction

Java Programming

Page 2: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

• Key to developing software is to apply the concept of abstraction.

• Method abstraction is defined as separating the use of a method from its implementation.

• The client can use a method without knowing how it is implemented.

• Details of implementation are encapsulated in the method and hidden from the client who invokes the method.

• Known as information hiding or encapsulation.

Page 3: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

• If you change the implementation, the client program will not be affected provided that you do not change the method signature.

• Implementation is hidden in a black box from the client:

Method Signature

Method Body

Black Box

Optional Input Optional Return Value

Page 4: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

The Math Class• Contains the methods needed to perform basic

mathematical functions.

• Exp: pow(a, b)

• Three categorizations: trigonometric methods, exponent methods, and service methods.

• Also provides two useful double constants PI and E(the base of natural logarithms) use Math.PI and Math.E in any program.

Page 5: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

Trigonometric Methodspublic static double sin(double radians)

public static double cos(double radians)

public static double tan(double radians)

public static double asin(double radians)

public static double acos(double radians)

public static double atan(double radians)

One degree is equal to PI/180 radians.

JDK 1.2 has toRadians(double angdeg) for converting an angle to radians and toDegrees(double angrad) for radians to degrees.

Page 6: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

Exponent Methodspublic static double exp(double a)

//**Returns e raised to the power of a (e^a) */

public static double log(double a)

//**Returns the natural log of a (ln(a) = logbase e(a))*/

public static double pow(double a, double b)

//return a raised to the power of b

public static double sqrt(double a)

//return the square root of a */

Page 7: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

Rounding Methodspublic static double ceil(double x)

//x rounded up to its nearest integer

public static double floor(double x)

//x rounded down to its nearest integer

public static double rint(double x)

//x is rounded to its nearest int. If x is equally close to two ints, the even on is returned as double.

public static int round(float x)

//return (int)Math.floor(x + 0.5)

public static long round(double x)

//return (long)Math.floor( x + 0.5)

Page 8: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

min, max, abs,and random Methods

• min & max methods are overloaded to return the min and maximum numbers between two numbers (int, long, float, or double)

• abs method is overloaded to return the absolute value of the number(int, long, float, and double)

• The Math class also has a powerful method , random, which generates a random double floating-point number greater than or equal to 0.0 and less than 1.0 ( 0 <= Math.random( ) < 1.0)

• http://java.sun.com/j2se/1.4/docs/api/index.html contains the documentation for the Math Class online.

Page 9: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

Write a program that generates ten random numbers between 0 – 100 (excludes 100) and computes the mean and standard deviation of these numbers.

Solution:

Define mean, standard deviation : mean is the average of the numbers and the standard deviation is a statistic that tells you how tightly all the various data are clustered around the mean in a set of data. You do not need to know how the formula for deviation is derived.

Page 10: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

public class ComputeMeanDeviation{public static void main(String[ ] args){

final int COUNT = 10; //Total #’sint number = 0; //Store a random #double sum = 0; //Store sum of the numbersdouble squareSum=0; //Store sum of the sqrs.//Create numbers, find its sum, and sqr sumfor(int i = 0; i < COUNT; i++){number = (int)Math.round(Math.random( )*1000);sum += number;//Add square to squareSumsquareSum += Math.pow(number,2);//same as number*number}//Find meandouble mean = sum / COUNT;//Find SDdouble deviation = Math.sqrt((squareSum – sum * sum / COUNT) / (COUNT – 1));//display resultSystem.out.println(“The mean is “ + mean);System.out.println(“The SD is “ + deviation);}

}

Page 11: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

Another Example• Write the methods for generating random

characters. The program uses these methods to generate 175 random characters between ‘!’ and ‘~’ (inclusive) and displays 25 characters per line.

• First off we have to look for the ASCII code representation for the two above characters and we find that ! is 33 and ~ is 126. Now we know we want to generate a Unicode whose integer is randomly chosen between 33 – 126 :

Value = (int)(33 + (126 – 33 +1) * Math.random(x));

Page 12: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

Since 0 <= (126 – 33 +1 )*Math.random(x) < 94,

33 <= 33 + (126 – 33 +1)*Math.random(x) < 127.

Therefore, 33 <=value <= 126. Thus (char)value is a character between ! and ~ inclusively.

So now the code:

Page 13: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

public class RandomCharacter{public static void main (String args [ ]) {

final int NUM_OF_CHARS = 175;final int CHARS_PER_LINE = 25;//Print random charactersfor (int i = 0; i < NUM_OF_CHARS; i++){

if(( i + 1) % CHARS_PER_LINE == 0)System.out.println(getRandomChar(‘!’, ‘~’));

else System.out.println(getRandomChar(‘!’,’~’) + “ “);}

}/**generate a random character between fromChar and toChar */

public static char getRandomChar(char fromChar, char toChar){//get the unicode of the characterint unicode = fromChar + (int)((toChar – fromChar + 1) * Math.random( ));//return the characterreturn (char)unicode;}

/**generate a random character */public static char getRandomChar( ){

return getRandomChar(‘\u0000’, ‘\uFFFF’);}

}

Page 14: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

• The RandomCharacter class contains 2 overloaded getRandomChar methods.

• getRandomChar(char fromChar, char toChar) method returns random char’s between fromChar and toChar.

• getRandomChar() returns a random char.• The latter method is implemented by invoking the former

method with the arguments ‘\u0000’ and ‘\uFFFF’. -- unicodes of the characters are between those two values.

• When a character is involved in numeric computation, its integer equivalent is used in the operand.

• toChar – fromChar + 1 yields the number of characters between fromChar and toChar so – (toChar – fromChar +1) * Math.random( ) yields a random double number that is greater than or equal to 0 and less than the above exp.

Page 15: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

Displaying Calendars• Write a program that displays the calendar for a

given month of the year. The program prompts the user to enter the year and the month, and then displays the entire calendar for the month.– 1. How would you get started on such a program?– 2. Would you immediately start coding?– 3. Details are important in the final program – concern

for details in the early stages may block the problem solving process.

– 4. To make problem solving easier – use method abstraction to isolate details from design and later implements the details.

Page 16: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

• First break this problem down into subproblems – two – 1. Get input from the user 2. Print the monthly calendar.

• ?Maybe start with a structure chart to help visualize the decomposition of the problem:

printCalendar

(Main)

readInput printMonth

Page 17: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

• We’ll use JOptionPane.showInputdialog method to display input dialog boxes

• User will enter year and the month.

• To print the calendar – you’ll need : which day of the week is the first day of the month and how many days the month has.

• With this you can print the title and body of the calendar.

• So printMonth can be decomposed into four subproblems: 1. Get the start day, 2. Get the number of days in the month, 3. Print title and 4. Print the month body.

Page 18: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

• ??How will you get the start day for the first month??• ??Are there classes available to help with this process??• Yes – simplest approach is to use the Date and Calendar

classes.• But – alternative approach.• 1. Assume that you now that the start day(startDay1800 =

3) for Jan 1, 1800 was Wednesday. • 2. You could compute the total number of days

(totalNumOfDays) between Jan 1, 1800 and the first date of the calendar month.

• 3. The start day for the calendar month is:(totalNumOfDays + startDay1800) % 7.

Page 19: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

• To compute the total days (totalNumOfDays) between Jan 1, 1800 and the first date of the calendar month, you could find the total number of days between the year 1800 and the calendar year and then figure out the total number of days prior to the calendar month in the calendar year. The sum of these two totals is totalNumOfDays.

• So – also need to know the number of days in a month and in a year.

• Remember:– Jan , March, May, July, Aug, Oct, and Dec have 31

– April, June, Sept, and Nov have 30

– Feb has 28 days during a regular year and 29 days during a leap year. A reg year has 365 days, whereas a leap year has 366 days.

Page 20: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

• Determine whether a year is a leap year :if ((year % 400 == 0) | | ((year % 4 == 0) && (year %

100 != 0)))

return true;

else

return false;

Introduce println() –

Think about our display – Three lines : month and year, a dash line, and the names of the seven days of the week as our calendar title.

Page 21: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

• Print the body, first pad some space before the start day and then print the lines for every week.

June, 2003-----------------------------------------

Sun Mon Tue Wed Thu Fri Sat

1 2 3

4 5 6 7 8 9 10

11 12 13 14

Page 22: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

• In general – a subproblem corresponds to a method in the implementation, although some are so simple that this is unnecessary.

• You need to decide which modules to implement as methods and which to combine in other methods.

• These decisions should be based on whether the overall program will be easier to read as a result of our choice.

Page 23: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

printCalendar(Main)

readInput

getStartDay

getTotalNumOfDays

printMonthBody

printMonthName

isLeapYear

getNumOfDaysInMonth

printMonth

printMonthTitle

Page 24: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

Top Down Approach• Implement one method in the structure chart at a

time -- from top to the bottom.

• Stubs can be used for the methods waiting to be implemented.

• A stub is a simple but incomplete version of the method.

• Using stubs enables you to test invoking the method from a caller.

• Implement main method first and then use a stub for the printMonth method

Page 25: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

Import javax.swing.JOptionPane;//PrintCalendar.java: Print a calendar for a given //month in a yearPublic class PrintCalendar {

/*Main method*/public static void main (String[ ] args) {

//Prompt user to enter yearString yearString = JOptionPane.showInputDialog( null, “Enter full year (i.e. 2003): “ ,

“User Input”, JOptionPane.QUESTION_MESSAGE);//Convert string into integerint year = Integer.parseInt(yearString);//Prompt for monthString monthString = JOptionPane.showInputDialog(null, “Enter month in number between 1 and 12: “,

“User Input”, JOptionPane.QUESTION_MESSAGE);//Convert string into integerint month = Integer.parseInt(monthString);//Print calendar for the month of the yearprintMonth(year, month);System.exit(0);}//** Stub for printMonth */Public static void printMonth(int year, int month) {

System.out.print(month + “ , “ + year); }}

Page 26: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

• Now implement the printMonth method.

• For methods invoked from printMonth you can create more stubs.

• This top-down incremental approach helps to isolate programming errors and makes debugging easy.

• The complete program is saved to the G drive under collaboration as PrintCalendar.java

Page 27: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

• The program does not validate user input.

• You could add an if statement to check input before printing calendar.

• Also could be modified to print a yearly calendar although it can only print months after 1800 – if you need an earlier year you’d have to modify the program.

• The calendar prints in a command window – you could modify it to print in a message dialog box.

• And you could use the Date and Calendar classes instead of the manual calculations.

Page 28: Method Abstraction Java Programming. Key to developing software is to apply the concept of abstraction. Method abstraction is defined as separating the.

• Method abstraction modularizes programs in a neat, hierarchical manner.

• Programs are written as collections of concise methods and are easier to write, debug, maintain and modify.

• Also establishes a writing style that promotes reusability.