True Object-Oriented programming: Dynamic Objects Static Object-Oriented Programming Reference Variables Eckel: 30-31, 41-46, 107-111, 114-115 Riley: 5.1, 5.2 D0010E Object-Oriented Programming and Design UML knowsabout - Håkan Jonsson 1 Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride 1
Loops and recursion Are loops and recursion really equally powerful? Yes But it s non-trivial to prove. <= : Any recursive Java program is transformed into an iterative program by the compiler. The instruction set of computers lack recursive parts, so instead the computer simulates recursion using iteration and a stack. => : Later on in the course, I will show how any of Java s loops can be transformed into (a semantically identical) recursion. So, for any iterative program there is a recursive program that computes the same result. In practice, there are some semantic differences. For example: Infinite recursion might exhaust the stack, and cause termination after a finite number if steps, while the corresponding infinite loop does not terminate the program. But note that neither computes anything sensible in this case. - Håkan Jonsson 4 Review: Java Programs A Java program consists of source code. The source code contains at least one class. Classes are written by programmers, have names that start with an upper-case letter, and, contain declarations of attributes like variables and methods. Yet, Java is object-oriented, not class-oriented. What does this mean? - Håkan Jonsson 5 Classes versus Objects Classes exist, and are created, when a programmer writes a Java program. The classes describe objects that will/can be created once the program is executed. In practice, everything that happens in a program takes place in methods of objects. The thread of execution shifts between methods when they call each other and when methods end. Like shown in the previous lecture. The program starts when the operating system calls the method main(). A class defines a type. - Håkan Jonsson 6 2
Classes versus Objects We differ between two stages in time: Compile-time: The time during which a program is being written and then compiled. Run-time: The time during which a program is executed. There are no objects during compile-time. There is only source code being written. There are no classes during run-time. There exists only static and dynamic objects. Objects are created and exist during run-time only. - Håkan Jonsson 7 Two kinds of objects per class One static object. Contains everything in the class declared with the modifier static. Is automatically created when the program starts. Exists until the program terminates. Attribute x in the static object described by class C is referred to by C.x (Has no type.) (Old style of programming.) Today s topic Arbitrary many dynamic objects. Contain everything in the class not declared static. Are created during runtime using the keyword new. Exist as long as they can be reached via a reference chain all the way from the static main-method. Are referred to via reference variables ( pointers ). refvar.x Each class defines a type. - Håkan Jonsson 8 Classes as templates So, a class can be thought of as a type definition and a template for a set of objects. Defines what objects of the type of the class contain/can do. Right now in the course, objects contain methods and Runnable code that can be invoked. Defines behavior. variables Hold data, or refers to data. Defines state. (There is more to come.) as declared in the class. Remember: Objects are used to represent information when the computer program executes. - Håkan Jonsson 9 3
2014-01- 29 Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride Example: The class A dynamic object of type represents a signal that can be turned on or off. Remember: During run-time, a program can create any number of dynamic objects. So, any number of signals can be created. The static object of the class holds statistics about all created signals. Remember: During run-time, there is exactly one static object per class (e.g. ). - Håkan Jonsson 11 public class { // declarations for the static object // of the class static int numberofs = 0; static int numberon = 0; static float percentageon() { if (numberofs == 0) { return 0f; } else { return (float) numberon / (float) numberofs; } } // declarations for dynamic objects of // type (on the next slide). - Håkan Jonsson 12 4
} public () { // this is a (the) constructor numberofs++; } boolean on = false; // holds the state, // initially off boolean ison() { // use this method to check return on; // signal status. } void seton() { if (on) { numberon++; } on = true; } void setoff() { if (on) { numberon--; } on = false; } ~numberofs : int ~numberon : int ~on : boolean ~percentageon() : float ~ison() : boolean ~seton() : void ~setoff() : void - Håkan Jonsson 13 Writing Classes Try to keep your classes in order, neat and tidy. If you like, you could for instance first list all static declarations and then all dynamic (non-static) ones. Makes it easier to understand what the static and dynamic objects contain. ~numberofs : int ~numberon : int ~on : boolean ~percentageon() : float ~ison() : boolean ~seton() : void ~setoff() : void public class ClassName { /* static declarations */ /* non-static declarations */ } Implementation Methods (etc) Variables and constants) Design UML - Håkan Jonsson 14 Constructors Dynamic objects are created by using the creation expression new and a constructor. s = new (); // s now refers to a signal A constructor contains initialization code that is executed when the object is created. In, it just increases the static variable numberofs. NB A constructor is not a method. NB A constructor has no return type nor is it void. - Håkan Jonsson 15 5
Constructors The name of a constructor must be identical to the name of the class including the capital letter in the beginning. Compare: Names of methods should start with a lower-case letter. If no constructor is declared in a class, Java adds a default constructor with no arguments. It is possible to... add parameters to constructors, which is common to do.... impose restrictions on from which code in a program objects can be created. - Håkan Jonsson 16 Overloading Constructors and methods in a class can be overloaded. X is overloaded if there are more than one declaration of X. All methods must return the same type of result. If X is overloaded, no two declarations of X may have exactly the same list of parameters. The method max can be overloaded like this: public static void max(int a, int b) public static void max(int x, int y, int z) public static void max(double u, double v) However, it is not allowed to have yet a method declared public static void max(int first, int second) since there is already a version of max with these parameters. System.out.println is an example of an overloaded method. There is one version of it for each set of parameters it is defined for. - Håkan Jonsson 17 This program creates and makes use of signals, i.e. dynamic objects of type. public class Test { public static void main(string[] args) { s1 = new (); } } s2 = new (); System.out.println(s1.isOn()); s1.seton(); System.out.println(s1.isOn()); if (s2.ison()) { s1.setoff(); s2.seton(); } System.out.println(s1.isOn()); System.out.println(s2.isOn()); System.out.println("% = " +.percentageon()); - Håkan Jonsson 18 6
Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride UML: Associations An association exists where a class knows about another class. Associations are represented by lines with arrows: A filled line means [the class] contains a [declaration of a] variable of this type. A dashed line means contains a parameter, local variable, or method returning a result of this type. A line starts at a containing class and points its arrow at the type. If the association is bidirectional, arrows are placed at both ends of the connecting line. A number at an arrow denotes multiplicity. The example to the right means: (Something in) Test has two (2) parameters/local variables/ results of type. 2 ~numberofs : int ~numberon : int ~on : boolean ~percentageon() : float ~ison() : boolean ~seton() : void ~setoff() : void - Håkan Jonsson 20 Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride 7
References Reference variables are used to interact with (reach) dynamic objects. The variable references, or points, at the object. A reference variable can be thought of as a road sign that can point at a dynamic object. Or be broken and not point at all (or just at the ground where it stands). Called illegal or null. Make sure you understand the difference between a road sign and what the sign points at. This is similar to the difference between a reference variable and the dynamic object referenced by the variable. t t - Håkan Jonsson 22 Example An illegal (or null) reference: Exists but doesn t point at all t t - Håkan Jonsson 23 Example s1; s2; s2 s1 Two reference variables of type are created - Håkan Jonsson 24 8
2014-01- 29 Example s1 = new (); A dynamic object of type is created... public () { // this is a (the) constructor numberofs++; } boolean on = false; // holds the state, // initially off... on == false We make s1 point at the new dynamic object (a signal ) s1 - Håkan Jonsson 25 Example s1.seton();... void seton() { if (on) { numberon++; } on = true; }... on == true Changes from false to true s1 - Håkan Jonsson 26 Example s2 = s1; on == true We make s2 point at what s1 points at s2 s1 - Håkan Jonsson 27 9
... Example s2.setoff(); void setoff() { if (on) { numberon--; } on = false; }... on == false s2 Changes back to false again s1 - Håkan Jonsson 28 Example s1 = null; on == false Changes s1 to illegal/null s2 s1 - Håkan Jonsson 29 Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride 10
Dynamic Objects Dynamic objects are the essence in objectoriented programming The static objects are very limited and neither necessary nor really used that much. They are not as flexible as dynamic objects and can unfortunately not be used in the same contexts. They are programmed much like old-fashioned imperative programming (c, for instance). However, we get them for free in Java. To understand how dynamic objects are used we need to go into how computer memory and variables function. - Håkan Jonsson 31... 50 1000...... 39" 40" 41" 42" 43" 44" 45" 46" 47" 48" 49" 50" 51"... Memory and the Storage of Data An integral part of a computer is its memory, which can be thought of as a (long) sequence of individual cells each of which can store a number. Each cell has a unique address. There are two basic forms of access to a cell. Direct addressing The cell at the address contains the data. Indirect addressing The cell at the address contains the address of the memory cell that contains the actual data. These two basic forms of access gives rise to two very different kinds of variables. - Håkan Jonsson 32 Variables In a program, a variable stands for the address of a memory cell. There are two kinds in Java: Primitive variables: The content of the memory cell contains data. Are stored in variable memory. Are used for integers, floating-point numbers, characters, and booleans. Reference variables: The content of the memory cell contains the address of the memory cell that contains the data. The data is stored in object memory. Used to keep track of dynamic objects. - Håkan Jonsson 33 11
Lifetime of variables The lifetime of any kind of variable spans from when it is allocated (created) until it is deallocated (destroyed). The lifetime is the period of time during which it exists. Variables that are static: Declared static so they belong to the static object. Allocated when the program starts and deallocated when the program ends. Variables that are dynamic: Declared in a class without the word static. Created when the object is created. Deallocated when the dynamic object holding the variable is deallocated. Recall that this happens when there is no longer a reference chain connecting main() and the object More on this at later lectures. - Håkan Jonsson 34 Lifetime of variables Variables that are automatic. Local variables in, and formal parameters to, methods and constructors. Temporary variables in compound statements. for (int i = 0; ) { i is alive here only } { int a; } a exists inside the pair { and }. Automatic variables live (exist) during the execution of the construct where they are created only. - Håkan Jonsson 35 Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride 12
Example: s We will now see how dynamic and static objects can be created and used in the context of signals and the class. The static and the dynamic objects have different functionality: A dynamic object of type represents a signal that can be turned on or off. The static object of the class holds statistics about all created signals. - Håkan Jonsson 37 The class public class { // declarations for the static object // of the class.. A (the only) dynamic variable Two static static int numberofs = 0;. variables static int numberon = 0; boolean on = false; // holds the state, // initially off static float percentageon() { if (numberofs ==0) { boolean ison() { // use this method to check A (the only) return 0f; return on; // signal status. static method } else { return (float) numberon } / (float) numberofs; } void seton() { } if (on) { // declarations for dynamic objects of numberon++; // type. } on = true; Three dynamic methods public () { A (the only) } numberofs++; constructor } void setoff() { if (on) {. numberon--;. }. ~numberofs : int on = false; ~numberon : int } ~on : boolean } ~percentageon() : float ~ison() : boolean ~seton() : void ~setoff() : void - Håkan Jonsson 38 Test using s1 and s2 are reference variables of type (pointer to) that refer to the two new signal objects Assume that we halt here during a run. false true false true % = 0.5 public class Test { public static void main(string[] args) { } } Creates two dynamic objects s1 = new (); of type s2 = new (); System.out.println(s1.isOn()); s1.seton(); System.out.println(s1.isOn()); if (s2.ison()) { s1.setoff(); Calls the method setoff in the object referred to by s1 and seton in the object s2.seton(); referred to by s2 } System.out.println(s1.isOn()); System.out.println(s2.isOn()); System.out.println("% = " +.percentageon()); - Håkan Jonsson 39 13
A snap-shot at the sbjects Dynamic objects on == false on == true s1 numberofs == 2 s2 numberon == 1 Test Static objects - Håkan Jonsson 40 Access to objects of a class Everything in the static object is accessible by all dynamic objects. The static object is referred to using the name of the class and this is known before the program is executed. Nothing in a dynamic object is available to the static object, unless the static object has a reference to the object. Not even the dynamic object itself (of course). The static object is therefore often programmed to hold data and methods common to all the dynamic objects. Important to remember: Reference variables can only refer to dynamic objects, not static objects. Access to a dynamic object requires a reference to it. - Håkan Jonsson 41 Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride 14
A more extensive example We like to study how far a helicopter flies when directed to travel (in straight lines) to a sequence of destinations. The type Helicopter is defined in the class Helicopter. The main program, HelicopterMain, has a reference variable h that points to a helicopter with call sign Z 41. This means there will be a filled line with an arrow in the UMLdiagram (not a dotted one). This helicopter is then requested to fly between given coordinates. Finally, we print h s callsign, currently location, and distance flown. NB The class Helicopter contain parts that are hard to understand (yes) at this point in the course and that will be the topic of upcoming lectures. package l03.ex2; public class HelicopterMain { public static Helicopter h = new Helicopter("Z 41"); public static void main(string[] args) { h.flyto(65, 40); h.flyto(-43, 74); System.out.println(h.callSign() + " is at (" + h.getx() + ", + h.gety() + ") and has flown " + h.distanceflown() + " km."); } } 1 HelicopterMain Helicopter package l03.ex2; public class Helicopter { private String callsign = ""; private long rtx = 0L, rty = 0L; private double distanceflown = 0.0d; public Helicopter(String name) { callsign = name; } public void flyto(long x, long y) { double dx = Math.abs(x - rtx); double dy = Math.abs(y - rty); distanceflown += Math.sqrt(dx * dx + dy * dy); rtx = x; rty = y; } public String callsign() { return callsign; } public long getx() { return rtx; } public long gety() { return rty; } public double distanceflown() { return distanceflown; } } Prints: Z 41 is at (-43,74) and has flown 189.54712645011404 km. Another snap-shot at objects Helicopter callsign== Z 41 rtx == -43 rty == 74 distanceflown == 189.54712645011404 h Helicopter HelicopterMain - Håkan Jonsson 45 15
Classes and objects Constructors and overloading Associations in UML References and reference variables Memory access methods and variables Example: s Example: The helicopter ride 16