1 of 30

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 0 - 3.

1

2 of 30

Object Orientated Programming Paradigm (OOP)

Own Classes - Exercises

Has-a” (Aggregation / Composition) = Objects that Contain Objects, final

2

3 of 30

3

LEARNING OBJECTIVE

Define instance variables for the attributes to be initialized through the constructors of a class.

Declare variables of the correct types to represent primitive data.

4 of 30

4

ESSENTIAL KNOWLEDGE

An object’s state refers to its attributes and their values at a given time and is defined by instance variables belonging to the object. This creates a “has-a” relationship between the object and its instance variables.

5 of 30

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).

5

6 of 30

Trees

  • What smaller objects does this simple tree model consist of?
  • Could an object of type Tree contain an instance variable that points to a Cone?

6

7 of 30

“Has-a” (Aggregation) = 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 (aggregation).
  • 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 values) within them.

7

8 of 30

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 a 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).

8

How many objects are there?

3:

    • Tree object
    • Cone object
    • Cylinder object

?

9 of 30

Ways to declare & assign a reference variable

  1. 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.

  1. 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.

9

Some constructors may require certain information called “actual” parameters written inside the brackets in a specific order separated by ,.

null/nothing

10 of 30

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: getVolume().
  • The area: - getArea():
    • (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 “tree's” surface area.

10

Continued on the next slide.

Tree

Cylinder

Cone

UML Diagram (without variables and methods)

one-to-one

11 of 30

Trees

  • Write the Tree class.
    • 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.

11

Tree

- branches : Cone

- trunk : Cylinder

- x, y, z : int

+ Tree(heightBranches, radiusBranches, heightTrunk, radiusTrunk : double, x, y, z : int)

+ getVolume() : double

+ getArea() : double

+ grow(double rate) : void

+ toString() : String

UML Diagram (with variables and methods)

Key:

- private

+ public

# protected

constructor

12 of 30

Forest

12

Tree

Cylinder

Cone

UML Diagram (without variables and methods)

Forest

one-to-many

one-to-one

Forest

- trees : Tree[]

+ Forest(size : int)

+ setTree(tree: Tree) : void

+ toString() : String

UML Diagram (with variables and methods)

Place each Tree in the next available location in trees.

13 of 30

Advantages & Disadvantages of “has-a” aggregation

  • https://www.baeldung.com/cs/inheritance-aggregation
    • Click the link above and scroll down to section 5 (first column of the table).

13

14 of 30

Forest

Answer in your comments:

    • How many objects in a forest of 4 trees? Explain.
    • Why is it sensible not to have setter methods of x, y & z of a tree?
    • Object instance variables are initialised by default to what? What does this mean?
    • When and why can we just write trees[i] when we really mean trees[i].toString() (see example below)?
      • e.g.

str += trees[i] + "\n\n";

14

15 of 30

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:
      1. Represents one month of weather.
      2. Records the high temperature for each day of the month.
      3. Has methods to access and change data.
      4. 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?

15

Continued on the next slide.

16 of 30

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 hours in each Day.

16

Continued on the next slide.

17 of 30

Weather Report

  • 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 (temps & valid)
    • final int ERRORFLAG = 999; // See later slides for details.

17

Continued on the next slide.

Remember that all should instance variables should be private.

18 of 30

Weather Report

  • A parametrised constructor
    • 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 will initialise the variables month, year & daysInMonth but it will only create the temps & 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?

18

Continued on the next slide.

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.

?

19 of 30

Weather Report

  • A parametrised constructor
      • 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 use a daysInMonth() method which will use an isLeapYear() method to compute this.
          • See later for details on how to write these methods.

19

Continued on the next slide.

20 of 30

Weather Report

  • constants

/* 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.*/

private final int ERRORFLAG = 999;

20

21 of 30

Weather Report - Methods:

  • isLeapYear(int year)

return ((year%4 == 0) && (year % 100 != 0)) || (year % 400 == 0);

  • daysInMonth(int m, int y)

if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12)

return 31;

else if (m == 4 || m == 6 || m == 9 || m == 11)

return 30;

else if(m == 2)

if (isLeapYear(y))

return 29;

else

return 28;

else

return ERRORFLAG;

21

22 of 30

Weather Report - Methods:

  • getTemp(int dayNumber)
    • Error check for a dayNumber being out of range or if no valid data 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.

22

// 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 ( (jan.setTemp(day, highestTemp) == 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 ignored (unused & lost). */

23 of 30

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 countValidDays() returns 0 (& main() should produce a suitable error message).

23

Continued on the next slide.

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 86 or earlier if necessary).

24 of 30

Weather Report

  • Write a Year class to keep track of the 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.
  • 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.

24

Continued on the next slide.

25 of 30

Weather Report

  • Answer the following questions in your comments:
    1. Is an array an object?
    2. What value are arrays of boolean initialized to? Why is this important in relation to the valid array?
    3. What does final mean in Java?
    4. What happens to a Month object when the program finishes?
    5. What is the array months full of immediately after it is declared?

25

26 of 30

StringArray

  • Write a StringArray class with a main() method.
    • Declare and construct an array ‘strArray’ to keep track of 8 strings.
    • 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.

26

Continued on the next slide.

27 of 30

StringArray

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

27

28 of 30

String[] args

  • 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" “stringC"
      • java StringDemo “123” “0045.7”
      • java StringDemo “23” “87” "13” "67” "-42”
    • How can a program tell how many command line arguments it has been given?
      • Comment on this.

28

29 of 30

String[] args

  • How can a program tell how many command line arguments it has been given?

29

30 of 30

Grade yourself

  • Grade yourself on the vocabulary and learning objectives of the presentation.

30