程序代写代做代考 clock compiler Java FIT9131

FIT9131
Week 4
Programming Foundations FIT9131
Object creation and interaction Week 4
1

FIT9131
Week 4
2
Lecture outline
•Design :
• Abstraction & modularisation
• Class and object diagrams
•Object Interactions :
• Primitivetypesandobjecttypes
• Creating new objects
• Passing information between objects
• Formalparametersandactualarguments
• Return values from methods
• Method overloading
• Multiple constructors

FIT9131
Week 4
Abstraction and models
• Abstraction is the ability to ignore details of parts to focus attention on a higher level of a problem.
• In a program, we choose the attributes and behaviour that are relevant to the problem we are trying to solve – and we ignore the rest.
• Using the process of abstraction we create a model that is a simplification of the real situation, strictly relevant to the problem to be solved. E.g. imagine if you are booking an movie ticket online – what information do you need to provide to the cinema’s booking system? What information is not needed?
3

FIT9131 Week 4
Modularisation
• Modularisation is the process of dividing a whole entity (eg. a problem to be solved) into smaller and well-defined parts, which can be built and examined separately, and which interact in well-defined ways. E.g. consider the process of designing a car – is it better/easy to design and build the entire car at once, or design the components individually and then combining them?
• In programming, the techniques of Modularisation and Abstraction are often used to deal with complexity. As programs become larger and more complicated these techniques become increasingly important.
4

FIT9131
Week 4
Example : Digital clocks
Two different designs – but we can see some obvious common properties
5

FIT9131 Week 4
Design : A simple digital clock
What attributes would a clock have?
What behaviour would you want for a clock?
6

FIT9131 Week 4
Modularising the clock display
7
Choices :
One four-digit display?
Or, 2x two-digit displays?

FIT9131
Week 4
Implementation
// represents a 2-digit display
public class NumberDisplay
{
private int limit; private int value;
Constructor and
methods omitted…
}
note how these consist of 2 x int type attributes : one to represent the 2-digit display, and another to represent an upper limit for the digit display.

NumberDisplay
This example is in Chapter03 of the sample projects. 8

FIT9131 Week 4
Implementation
// represents a Clock, which consists // of 2 x 2-digit displays
public class ClockDisplay
{
private NumberDisplay hours; private NumberDisplay minutes; private String displayString;
Constructor and
methods omitted…
}
9
note how these consist of 2 x NumberDisplay type attributes

ClockDisplay

FIT9131 Week 4
Class relationship diagram
So a ClockDisplay object will contain some NumberDisplay objects (two, to be exact)
10

FIT9131
Week 4
Object diagram
myDisplay: ClockDisplay
hours minutes
displayString
: NumberDisplay limit
NumberDisplay
object
ClockDisplay
object
value
11
: NumberDisplay limit
value
NumberDisplay
object
24
11
11:03
60
3

FIT9131 Week 4
Object diagram (BlueJ Inspector)
12

FIT9131
Week 4
Variables of primitive types vs. object types
A primitive type is one of the Java built-in basic data types, e.g. int, double, char, boolean. The name of the variable is a memory location that stores the actual value of that variable.
An object type may be pre-defined in the Java system (e.g. String) or user-defined (e.g. NumberDisplay). The name of the variable is a memory location that stores the address of that object (which stores the values of its fields). These are also called reference variables.
13

FIT9131 Week 4
Primitive types vs. object types
note : the variable name is a reference to the actual object
Object
ObjectType a;
object type (any object type, eg. String, Student, etc)
14
int a;
32
note : the variable stores the actual value
primitive type

FIT9131 Week 4
Primitive types vs. object types
Consider these 2 variables :
ObjectType a;
ObjectType b;
Object
and compare them to these 2 :
int a;
Object
15
32
int b;
17

FIT9131
Week 4
Primitive
On the previous slide, we had 4 variables, 2 of primitive types (int) and 2 of object types (ObjectType).
What would happen if we now execute this code :
b = a;
for the primitive variables, versus for the object variables?
types
vs. object types
16

FIT9131
Week 4
Results of the assignments
ObjectType a;
ObjectType b;
Object
int a;
Object (or Reference ) type assignment
b = a;
17
32
Primitive type assignment
int b;
32

FIT9131
Week 4
Source code: NumberDisplay
public NumberDisplay(int rollOverLimit)
{
limit = rollOverLimit;
value = 0; }
public void increment() {
value = (value + 1) % limit;
}
What is happening here?
18

FIT9131
Week 4
Source code: NumberDisplay
public String getDisplayValue()
{
if (value < 10) return "0" + value; else return "" + value; } 19 What is happening here? FIT9131 Week 4 Objects creating other objects public class ClockDisplay { private NumberDisplay hours; private NumberDisplay minutes; private String displayString; public ClockDisplay() { declaring other objects as attributes initialising those attributes, by creating 2 new objects } } 20 hours = new NumberDisplay(24); minutes = new NumberDisplay(60); updateDisplay(); Calling the NumberDisplay constructor twice, with different values FIT9131 Week 4 What does this mean??? On the previous slide, we declare that two of the attributes of the class ClockDisplay are of type NumberDisplay. We then initialise those attributes by creating two NumberDisplay objects within the ClockDisplay constructor. What this mean is : whenever a ClockDisplay object is created, it actually contains 2 NumberDisplay objects (as shown on the next slide) as its attributes. 21 FIT9131 Week 4 Object diagram myDisplay: ClockDisplay hours minutes displayString : NumberDisplay limit NumberDisplay object ClockDisplay object value 22 : NumberDisplay limit value NumberDisplay object 24 0 00:00 60 0 FIT9131 Week 4 Formal Parameters versus Actual Arguments in class NumberDisplay: public NumberDisplay(int rollOverLimit) formal parameter in class ClockDisplay: hours = new NumberDisplay(24); actual argument 23 FIT9131 Week 4 Creating a new object When we instantiate an object from a class, we use the new operator. Eg : new NumberDisplay(24) This statement allocates a block of memory big enough to hold a NumberDisplay object, and calls the constructor to initialise the values of itsfields. Thenewoperatorreturnstheaddress of the beginning of that block of memory. 24 24 0 FIT9131 Week 4 Naming a new object Usually, we want to give an object a name so that we can refer to it afterwards. E.g : hours = new NumberDisplay(24); This statement puts aside enough memory to hold the address of a NumberDisplay object, and “name” that memory location hours. hours We say that hours is a reference to the actual hours object. This is also called a reference variable. 25 24 0 FIT9131 Week 4 Object interaction Objects communicate with each other by sending messages. There are three components of a message sent to an object: • the name of the object that is the receiver of the message • the action that the receiver is requested to take • in parentheses, any extra information the receiver needs to know In Java, the syntax for a message depends on whether it is an internal or external method 26 FIT9131 Week 4 Method calling example Consider this method in ClockDisplay public void timeTick() { External method call minutes.increment(); if(minutes.getValue() = = 0) // it just rolled over! hours.increment(); updateDisplay(); 27 } Internal method call FIT9131 Week 4 Method calls internal method call – when the method is called from within another method of the same class, e.g. updateDisplay(); updateDisplay() is in the same class (ClockDisplay) as timeTick() external method call – when calling a method of a different class, e.g. minutes.increment(); System.out.print(minutes.getValue()); hours.increment(); These methods are from a different class (NumberDisplay). External method calls use the dot (.) notation : object . methodName ( parameter-list ) 28 FIT9131 Week 4 Passing information in a message When an object needs some extra information in order to fulfill a request, this information can be passed with the message. The extra information that is passed is called actual arguments. This information is transferred to the formal parameters defined in the method header. We have seen these many times before. 29 FIT9131 Week 4 Example : Formal parameters A method has a header and a body. Consider the setValue method of the NumberDisplay class: Method header public void setValue(int replacementValue) if ((replacementValue >= 0) &&
{} (replacementValue < limit)) Method body } value = replacementValue; This method has a formal parameter called replacementValue which is an int. When this method is called, it expects to be passed an integer value. replacementValue is called a formal parameter. It is a placeholder for a value that will be supplied when the method is invoked. 30 FIT9131 Week 4 Example : Actual arguments The method is called by using a NumberDisplay object and asking it to invoke the method, eg : hours = new NumberDisplay(24); hours.setValue(12); The integer values 24 & 12 are the actual arguments that were given to the methods when they are invoked. Another example : int newValue = 12; hours.setValue(newValue); The setValue method sees only the value 12. It does not see the name of the variable (ie. newValue) that contains the value of the actual argument. 31 FIT9131 Week 4 Methods with multiple parameters The method setTime(...) in ClockDisplay changes the fields of a ClockDisplay object. public void setTime(int hour, int minute) { hours.setValue(hour); minutes.setValue(minute); updateDisplay(); } 2 formal parameters A call to this method would need to pass two actual arguments, e.g. aClockDisplay.setTime(13, 49); 32 FIT9131 Week 4 Rules for Matching formal parameters with actual arguments The actual arguments passed to a method must match the formal parameters in all of the following: • number • type • order The compiler assumes that the first actual argument matches the first formal parameter, the second actual argument matches the second formal parameter, etc. The names of formal parameters do not have to match the names of the actual arguments. The called method does not see the names, it sees only the values being passed in. For example, on the previous slide, the parameter hour will be assigned the value 13 and minute will be assigned 49. 33 FIT9131 Week 4 Passing basic data types as parameters If a parameter is of a primitive data type, when the formal parameter comes into existence it is a copy of the actual argument. Therefore, any changes made to the formal parameter inside the method will not affect the value in the caller's memory area. This kind of parameter passing is known as call-by-value. 34 FIT9131 Week 4 Example : Call For example, if the setValue method is called by some other method, like this : - by - value int newValue = 12; hours.setValue(newValue); note : these are 2 separate “variables” – they just happen to have the same value as they are copies of each other 12 newValue 12 replacementValue Memory belonging to the other (calling) method 35 Memory belonging to setValue FIT9131 Week 4 Passing objects as parameters When an object is passed as a parameter, what is passed to the method is a copy of the reference to the object. A change to the state of the formal parameter produces a change in the state of the actual argument. This kind of parameter passing is known as call-by-reference. note : the 2 references are “pointing” to the same object 36 Reference to object in calling method Reference to object in called method Memory for object in calling method FIT9131 Week 4 becomes Returning values from methods A value returned from a method replaces the call to the method. Eg : NumberDisplay aNumberDisplay = new NumberDisplay(); System.out.println(aNumberDisplay.getValue()); System.out.println(0); ClockDisplay aClockDisplay = new ClockDisplay(); if (minutes.getValue() = = 0) ... if (0 = = 0) ... if (true) ... 37 becomes becomes FIT9131 Week 4 Methods with no parameter and no return values Eg : this method in the ClockDisplay class: public void updateDisplay() { no formal parameter displayString = hours.getDisplayValue() + “:” + minutes.getDisplayValue(); } This method can be invoked by an expression like : updateDisplay(); 38 no actual argument FIT9131 Week 4 Method signatures A method has a signature that specifies what parameters it takes when it is called. public int getAge() public String getName() public boolean setAge(int anAge) private boolean validAge(int anAge) The signature is the method name plus the parameter list. The compiler cares only about the types in the parameter list, not the names of the formal parameters. 39 FIT9131 Week 4 Method Overloading It is possible to have more than one method (or constructor) with the same name, but different signatures, in a class declaration. This is called method overloading. The compiler knows which method you want to call by looking at the signature of the methods. If it can't find a signature that matches the way you have called that method, it gives you an error message. An example of overloading can be seen with the multiple constructors in the ClockDisplay class : public ClockDisplay() public ClockDisplay(int hour, int minute) 40 FIT9131 Week 4 Default constructor of class hours = new NumberDisplay(24); minutes = new NumberDisplay(60); updateDisplay(); } NB. A Default Constructor has no formal parameter(s) If you do not write a constructor for a class, Java puts one in for you. Good programming practice – always write your own constructor! 41 ClockDisplay public ClockDisplay() { FIT9131 Week 4 Another constructor (“overloaded”) public ClockDisplay(int hour, int minute) { hours = new NumberDisplay(24); minutes = new NumberDisplay(60); setTime(hour, minute); } As long as the signatures are all different, the compiler has no problem with these. 42 ClockDisplay FIT9131 Week 4 Overloading other methods We can also overload any other methods in exactly the same way, as long as the two methods with the same name have different signatures. Eg - consider this method : public boolean setGrade(char aCharacter) { if (validGrade(aCharacter)) // check if parameter is valid { grade = aCharacter; // assume grade is an attribute return true; } return false; } 43 FIT9131 Week 4 An overloaded version of public boolean setGrade(String aString) { char aCharacter = aString.charAt(0); if (validGrade(aCharacter)) { grade = aCharacter; return true; } return false; } OR, more efficiently (same result): public boolean setGrade(String aString) { char aCharacter = aString.charAt(0); return setGrade(aCharacter); 44 } setGrade Returns the first character in the string FIT9131 Week 4 Which method is called? When you call the setGrade method, Java will pick one version or the other to execute, depending on what type of data is passed to it. eg : setGrade('P') will cause the first version to be executed, and setGrade("P") will cause the second version to be executed. As the two versions have different signatures, there is no confusion for the compiler. 45 FIT9131 Week 4 The The this keyword is used resolve name conflicts. It means “the current object” i.e., the object that has been asked to invoke this method. It can be used to access a attribute (field) when there is a more ‘closely’ defined variable with the same name. For example, in the following constructor the three parameters have the same names as the attributes – so the code would not work : public MailItem(string from, String to, String message) { from = from; to = to; message = message; } 46 this keyword Problem : Java cannot differentiate between the attributes and the parameters, since their names are the same FIT9131 Week 4 The We need something to differentiate the attributes from the formal parameters : public MailItem(string from, String to, String message) { this.from = from; this.to = to; this.message = message; } The this.from refers to the from attribute in the current object, etc. The from refers to the from formal parameter in the current method, etc. 47 this keyword No confusions here!!! FIT9131 Week 4 Cleaner solution? A cleaner (& recommended) solution is : use different names for the attributes and the formal parmeters – eg. we could have named the parameters above “sender”, “receiver”, “newMessage”. Then we wouldn’t need to use the this keyword at all here. Eg. Use different names for different things : public MailItem(string sender, String receiver, String newMessage) { from = sender; to = receiver; message = newMessage; } 48 Even less confusions here!!!