Presentation is loading. Please wait.

Presentation is loading. Please wait.

Review of Previous Lesson

Similar presentations


Presentation on theme: "Review of Previous Lesson"— Presentation transcript:

1 Review of Previous Lesson
26/05/2019 Review of Previous Lesson State as many Vocabulary words and Learning Objectives that you remember from the last lesson as you can. Remember to grade yourself from

2 Object Orientated Programming Paradigm (OOP)
26/05/2019 Object Orientated Programming Paradigm (OOP) Own Classes - Exercises “Has-a” = Objects that Contain Objects, final

3 Language Features and other Testable Topics
26/05/2019 Tested in the AP CS A Exam Notes Not tested in the AP CS A Exam, but potentially relevant/useful Variables private instance variables: visibility (private), final Methods 9 public static void main(String[] args), command line arguments, Miscellaneous OOP “has-a” relationships,

4 Language Features and other Testable Topics
26/05/2019 Notes: 9. The main method and command-line arguments are not included in the subset. In free-response questions, students are not expected to invoke programs. In the AP Computer Science Labs, program invocation with main may occur, but the main method will be kept very simple.

5 26/05/2019 Write your own programs: Write your own programs from “scratch”. Of course you should use previous programs for reference, but write your code from “scratch” (do not copy and paste).

6 Trees What smaller objects does this simple tree model consist of?
26/05/2019 Trees What smaller objects does this simple tree model consist of? Could an object of type Tree contain a instance variable that points to a Cone?

7 “Has-a” = Objects that Contain Objects
26/05/2019 “Has-a” = Objects that Contain Objects As with real world objects, software objects are often composed of smaller software objects. Instance variables can also be reference variables. Object composition is sometimes called a “has-a” relationship between objects. In the real world objects can be directly part/embedded in other objects. However, in the software world, objects only have references/pointers to the objects (and primitive types) within them.

8 Can an object contain instance variables that point to other objects?
26/05/2019 Can an object contain instance variables that point to other objects? Yes: e.g. private Cone branches; private Cylinder trunk; It may feel like the Cone and Cylinder objects are directly part of the Tree object (a complete Cone object and complete Cylinder object are embedded in the Tree object). But in Java, a tree consists of a pointer to the branches and a pointer to a trunk (and some int variables). How many objects are there? 3: Tree object Cone object Cylinder object ?

9 Ways to declare & assign a reference variable
26/05/2019 Some constructors may require certain information called “actual” parameters written inside the brackets in a specific order separated by ,. null/nothing ClassName refVarName = new ClassName ( ); // This is the typical way you have mainly used until now. Declares a reference variable & the class of the object. Constructs a new object and a reference to that object is put in the variable. Sometimes parameters are needed when the object is constructed. ClassName refVarName; …. refVariableName = new ClassName( ) ; Declares a reference variable & the class of the object it will later refer to but no object is created. ClassName refVarNameOne, variableNameTwo, …; Declares multiple reference variables, potentially referring to objects of the same class but no objects are created. ClassName refVarNameOne = new ClassName ( ), variableNameTwo = new ClassName ( ) ; Declares multiple reference variables, constructs new objects and their references are assigned to the variables.

10 Trees A simple tree consists of a cone and a cylinder.
26/05/2019 Trees A simple tree consists of a cone and a cylinder. You should use the Cone & Cylinder classes written previously. A Tree has-a Cone A Tree has-a Cylinder An object of type Tree will contain instance variables that point to a Cone & a Cylinder. All you need is a cone for the branches and a cylinder for the trunk. We will also use x, y, & z for the location of a tree. The volume of the tree is the sum of the cone volume and the cylinder volume: volume(). The area: - area(): (Cone area + Cylinder area) – (2*area of the circle at the top of the Cylinder) The area of the circle at the top of the cylinder and its intersection with the base of the cone are not part of the solid's area. Continued on the next slide.

11 Trees Write a Tree class. 26/05/2019
As well as what has been discussed on the previous slide also include: A toString() method to display the position of the tree and the instance variables of the cone & cylinder. grow(double rate) Trees can grow at a certain rate (e.g. 0.10) which affects all dimensions. getter methods for x, y & z. Continued on the next slide.

12 Trees Answer in your comments: 26/05/2019
How many objects are there if are 2 Tree objects? Explain. Why is it sensible not to have setter methods of x, y & z of a tree?

13 Trees Answer in your comments: 26/05/2019
How many objects are there if are 2 Tree objects? Explain. 6: 2 trees 2 cylinders (1 for each tree) 2 cones (1 for each tree) Why is it sensible not to have setter methods of x, y & z of a tree? Because trees do not naturally move!

14 Trees 26/05/2019 Also write a Forest class that:
Constructs at least 4 Tree objects tree0, tree1, tree2, … . Has a default constructor. Has a setTree() method that accepts a Tree reference & an integer that says which instance variable to set and assigns it a corresponding reference variable e.g. if (treeNum == 0) tree0 = tree; if (treeNum == 1) tree1 = tree; Has a getTree() method that returns a specified tree. Has a toString() method which returns all trees created in one String variable e.g. String str = ""; if ( tree0 != null ) str += "Tree 0: " + tree0 + "\n"; Has area() and volume() methods. Write a separate class with a main() to demonstrate all methods.

15 Forest Answer in your comments: 26/05/2019
How many objects in a forest of 4 trees? Explain. Object instance variables are initialised by default to what? What does this mean? When and why can we just write tree0 when we really mean tree0.toString (see example below)? e.g. str += "Tree 0: " + tree0 + "\n";

16 Forest Answer in your comments: 26/05/2019 16
How many objects in a forest of 4 trees? Explain. 13: 1 forest 4 trees 4 cones 4 cylinders Object instance variables are initialised by default to what? What does this mean? Object instance variables are initialised by default to null. When a reference contains null it is not pointing to any object. When and why can we just write tree0 when we really mean tree0.toString? The toString() method is automatically called when an object is treated as a String (e.g. in expressions that result in a String or printing them to the console). 16

17 26/05/2019 Weather Report Write a program to keep track of weather for your city by recording the high temperature of each day for a month. Write a Month class that can construct an object that: Represents one month of weather. Records the high temperature for each day of the month. Has methods to access and change data. Has methods that summarize the data. In a month of up to 31 days there will be up to 31 values to store. What do you propose could be done to store all this data? Continued on the next slide.

18 26/05/2019 Weather Report In a month of up to 31 days there will be up to 31 values to store so this is a good place for an array. As we only need to store one temperature per day, you should store these temperatures in an array of ints. If we needed to store multiple measurements (temperature & pressure for every hour of the day in a day) we would use a Day class that represents each day and have an array of Days in each Month. Continued on the next slide.

19 Weather Report A Month might not have valid data for every day.
26/05/2019 A Month might not have valid data for every day. Some days might be in the future, and other days might have been missed. You will deal with this by using an array named valid, which will contain a true/false value for each day to indicate if the temperature for that day is valid. When initially constructed, each cell of an array is initialized to a default value. The array temp[] will be filled with zeros, but these are not actual data for the days. The role of the array valid[] is to show which days have valid data. e.g. If (say) valid[5] is true, then the corresponding temperature for day 5 is valid. Boolean arrays are automatically initialised to false, so just after construction no days have valid data. Instance variables: int month; // 1 == January int year; // year as an int, eg 2017 int daysInMonth; // number of days in this month 2 arrays (temp & valid) final int ERRORFLAG = 999; // See later slides for details. Continued on the next slide.

20 ? Weather Report A parametrised constructor 26/05/2019
The temperature for each day will be added after the Month object has been built. The constructor only needs to know the year and month number so it set month, year & daysInMonth but it will only create the temp & valid arrays (not populate them). How can we declare an array on one line and create an array on another? What do you think the size of the arrays should be? dataType[] arrayName; // Establishes the fact that intArray is an int array variable but no array actually exists yet, only a reference to the array is created. arrayName = new dataType[arraySize]; // Creates an array. ? Continued on the next slide.

21 Weather Report A parametrised constructor 26/05/2019
Each array will have a length of 32 to make the use of the array more convenient to (index 1 for day 1, array index 2 for day 2, and so on). This means that the 0 cell in each array will not be used. This is a common programming trick which may seem like a waste as, in addition to wasted 0 cell, not all months have 31 days, but a few unused bytes in modern computers is not an issue. The instance variable daysInMonth contains the number of days in a particular month. The constructor will need to computes this based on the year and month supplied as parameters. Use a series of if statements and a isLeapYear() method to compute this. See later for details on how to write a isLeapYear() method. Continued on the next slide.

22 26/05/2019 final The reserved word final tells the compiler that the value will not change. e.g. final datatype thisVariableWillNotChange = …. The names of constants (variables declared as final) can follow the same rules as the names for variables or use only capital letters.

23 Weather Report constants 26/05/2019
/* Will be used as a return value by some methods to flag an error. The caller will be expected to check the return value before using it. Using the same variable name throughout a program’s code will improve readability and consistency. See next slide for more details.*/ final int ERRORFLAG = 999;

24 Weather Report - Methods:
26/05/2019 isLeapYear( int year ) return ((year%4==0) && (year%100!=0)) || (year%400==0); getTemp(int dayNumber) Error check for a dayNumber being out of range and return ERRORFLAG if so. setTemp(int dayNumber, int temp) Error check for dayNumber being out of range and return True if dayNumber is valid and False if it is not. Note that to use this feature effectively main() should check if setTemp returns False and act accordingly: if ( !jan.setTemp(day, highestTemp ) ) /* This still calls .setTemp on jan & checks if it returns false but is a more professional, neater & elegant way to write if … = False. */ System.out.println("error in input"); /* Also note that jan.setTemp(day, highestTemp ) on its own will also compile and execute but as the return value is never examined or stored anywhere it will just be unused & lost. */ Continued on the next slide.

25 Weather Report - Methods:
26/05/2019 Weather Report - Methods: toString() To return the month/year, all days & valid temperatures as one string (with / & line breaks as appropriate) for display. e.g. countValidDays() Count the number of days with valid data. avgTemp() Compute the average temperatures for all valid days. Return ERRORFLAG if count < 0 (& main() should produce a suitable error message). Use an String Escape Sequence for line breaks. For reminder see “nested for” (slide 9). For reminders on how to store primitive data types in String variables see “Strings” (slide 71 or earlier if necessary). Continued on the next slide.

26 26/05/2019 Weather Report Write a Year class to keep track of the high temperature for each day for a year. Each Year object will be composed of 12 Month objects in an array Months[]. It is convenient to number months starting at one, so the array would be 13 cells long, but cell 0 would not be used. This is different from the array in Month objects where each cell of the array is a primitive type. Optional extension: You may create your own suitable methods for the Year class. Write a separate class with main() to demonstrate the use of both classes and any methods of each. Continued on the next slide.

27 Weather Report Answer the following questions in your comments:
26/05/2019 Weather Report Answer the following questions in your comments: Is an array an object? What value are arrays of boolean initialized to? Why is this important in relation to the valid array? What does final mean in Java? What happens to a Month object when the program finishes? What are reference variables automatically initialized to?

28 Weather Report Answer the following questions in your comments:
26/05/2019 Answer the following questions in your comments: Is an array an object? Yes. What value are arrays of boolean initialized to? Why is this important in relation to the valid array? Boolean arrays are automatically initialized to false. So just after construction no days have valid data. What does final mean in Java? final is used for named constants. What happens to a Month object when the program finishes? It vanishes. What are reference variables automatically initialized to? null The array month starts out with 13 cells, each containing the special value null.

29 StringArray Write a StringArray class with a main() method. 26/05/2019
Declare and construct an array ‘strArray’ to keep track of 8 strings. You may or may not use cell 0 (your choice). Write a loop to ask the user for strings to populate strArray but allow the user to exit the loop at any time by entering a exit code of your choice. i.e. It is possible that some or all cells will be null. Write a loop to display each cell of the array. cell … strArray[…] Make sure to avoid printing null cells. Continued on the next slide.

30 StringArray Answer the following questions in your comments:
26/05/2019 StringArray Answer the following questions in your comments: What does this statement do? String str; Must all of the Strings pointed to by cells of the array be of the same length? Why might strArray[j].length() not always work? Explain what happens if the following statements occur in this order in a program? strArray[0] = “Hello”; strArray[0] = “Good-bye”;

31 StringArray Answer the following questions in your comments:
26/05/2019 Answer the following questions in your comments: What does this statement do? String str; It declares a variable str that can hold a reference to a String object. No object has been created. Must all of the Strings pointed to by cells of the array be of the same length? No. Each element of the array is of the same type a reference to a String, but the Strings themselves can be of different lengths. Why might strArray[j].length() not always work? No. Sometimes strArray[j] is null, so strArray[j].length() will not work. Explain what happens if the following statements occur in this order in a program? strArray[0] = “Hello”; strArray[0] = “Good-bye”; This will replace the reference in cell 0 with a reference to a new String, containing the characters "Good-bye" .

32 String[] args 26/05/2019 Finally, after all this time, we will look at this! (But note that AP CS does not require it.) The phrase String[] args says that main() has a parameter which is a reference to an array of String references. This array is constructed by the Java system just before main() gets control. The elements of the array refer to Strings that contain text from the command line that starts the program. Write a StringDemo class that anticipates the creation of a String array named args and attempts to print out the contents. for (int j=0; j < args.length; j++ ) System.out.println( "Parameter " + j + ": " + args[j] ); Now try starting the program with command line arguments. e.g. java StringDemo stringA stringB string java StringDemo java StringDemo How can a program tell how many command line arguments it has been given? Comment on this.

33 26/05/2019 String[] args How can a program tell how many command line arguments it has been given? Use args.length

34 5/26/2019 Grade yourself Grade yourself on the vocabulary and learning objectives of the presentation.


Download ppt "Review of Previous Lesson"

Similar presentations


Ads by Google