Object-Oriented Programming IB Computer Science Option D D1.1 Outline the general nature of an object • All objects have state and behaviour • State refers to what their attributes are • Behaviour refers to what they can do • In Java these correspond to fields and methods Object State Behaviour Dog Breed, name, colour Bark, wag tail, sleep Car Make, model, colour Accelerate, brake, turn RPG Character Class, race, name, spells, hit points Cast, fight, flee, heal • Task: Think of an object in the real world. What attributes give determine its state? What behaviours does it have? D.1.2 Distinguish an object and instantiation This is instantiation. We make an object of the Dog class. Once the object is instantiated we can use dot notation to set its fields and ask it to do things like bark and wag its tail. This is the Dog class. It's like a template. It defines what attributes dogs can have in our system, and what they can do. But remember, no dogs exist in our system until we instantiate them. D.1.2 Exercise In OOP, once we have instantiated a class we call it an object. Below are 10 class/object pairs mixed up. See if you can match them up. Example: Serena Williams is an instance of the Tennis Player class. Make sure you know which is the class, and which is the object (instance). Angela Jolie Lionel Messi University Aircraft Fraction Actress Princeton Boeing 747 Red Hot Chili Peppers ¾ Rock band Footballer D1.2 Object references Look back at the Java code two slides ago. The variable d is kept in a different place in the computer's memory from the dog object. They are associated with each other using a memory reference. Dog object at 0xF8275AB9 d String breed "Chihuahua" String name "Jeff" String colour "Brown" Methods: bark() sleep() 0xF8275AB9 wagTail() Informally we use arrows to show this relationship, but if you ever get confused with arrows, it can be useful to remember that really they are memory references. d Dog Object D1.2 More on object references Dog d; d d = new Dog(); d Dog object Dog e; d Dog object e e = d; d Dog object e D1.3 Construct unified modelling language (UML) diagrams to represent object designs Student - firstName: String - lastName: String - gpa: double - totalStudents: int + getFirstName(): String + setFirstName(name: String): void + getLastName(): String + setLastName(name: String): void + getGpa(): double + setGpa(gpa: double): void + getTotalStudents(): int There is a lot to UML but I don't think you will need more than this It specifies a class without you having to code it UML is used in systems design Class name fieldName: type methodName(argName: type): return type Plus (+) means public Minus (-) means private Underlined means static D1.3 Construct unified modelling language (UML) diagrams to represent object designs D1.4 Interpret UML diagrams Task 1: Create a UML diagram to specify a Customer for a bank. There should be some way of identifying different customers, together with a current account balance and the ability to withdraw, deposit and check their balance. Add any other fields or methods you think would be useful. Task 2: Implement the following class in Java. You don't need to code the bodies of the methods, just the fields and method signatures. Extensions: Provide getters and setters Implement the method bodies Fraction - int: numerator - int: denominator + add(fraction: Fraction): Fraction + multiply(fraction: Fraction): Fraction + getDecimal(): double D1.5 Describe the process of decomposition into several related objects Decomposition means "breaking down" into component parts. Administrative Principal Secretary Employee Faculty Maintenance All of the people who work at your school are employees. But there are different types of employee, so we can decompose employee. D1.5 Describe the process of decomposition into several related objects We decompose objects to understand how they work. A complex object is made up of many simpler objects. The simpler objects are easier to understand. D1.5 Describe the process of decomposition into several related objects Simple games programming is an excellent way to practice object decomposition This is a game of "Sub Hunt" that I programmed in Scratch Watch the video and then decompose the game into objects Can any of those objects themselves be decomposed? Choose one of the simple games listed here: http://retrosnob.wordpress.com/201 3/10/03/game-ideas/ Produce an object decomposition D1.6 Describe the relationships between objects for a given problem. The IB mentions three kinds of relationship that can exist between objects: Is Inheritance A Lotus Esprit is a car Has Composition/Aggregation A smartphone has a CPU Uses Dependency A project manager uses a Gantt Chart The last two are sometimes difficult to separate. A good rule of thumb is that if the component is built-in or somehow essential, then you have a composition relationship. Similarly if the component can exist on its own, or can be used by lots of different objects, then you have a dependency relationship. D1.6 Describe the relationships between objects for a given problem. Inheritance hierarchy Bicycle MTB Road Bike Hybrid A mountain bike is a bicycle, a road bike is a bicycle, a hybrid is a bicycle. Characteristics that the Bicycle has are inherited by the subclasses. However, the subclasses can override them if they want to. Notice that Square has no variables or methods. It has inherited them from Shape. Circle, on the other hand, has overridden its getArea() method. Inheritance is effected by the use of the extends keyword in Java. D1.6 Describe the relationships between objects for a given problem. Containment hierarchy Book Club Members Collection Member Books on Loan Collection Book on loan Book The basic mechanics of a containment or composition hierarchy in Java. This is not meant to be an example of good programming practice! D1.7 Outline the need to reduce dependencies between objects in a given problem. Two classes are said to form a dependency if a change to one of them necessitates a change in the other. On large software projects this can cause significant problems. This is also known as high coupling. Decoupling is desirable and is what every software developer strives for. Encapsulation is one of many ways to reduce coupling. Most of the others are beyond the IB syllabus, such as the use of Interfaces, factory patterns and dependency injections. I think I'm going to change my Linked List class around a bit.… Aarrgh! My software uses that class. If you change it, my software might not work any more! D1.8 Construct related objects for a given problem The guide states "In examinations problems will require the students to construct definitions for no more than three objects and to explain their relationships to each other and to any additional classes defined by the examiners." I assume this means: Constructing UML diagrams from a textual description of a scenario. Constructing code from a textual description of a scenario. Constructing code from a set of UML diagrams. Students should study the sample question from the IB. Things to consider are: Is there an inheritance (is-a) relationship? If so, which is the superclass and which are the subclasses? What fields and methods does the superclass have? What different fields and methods do each of the subclasses have? (Remember that they will all inherit the fields and methods from the superclass.) Are there any containment/composition (has-a) relationships? Possible scenarios could be: Car, Vehicle, Motorcycle, Van Dog, Cat, Animal, Bird Salesperson, Factory Worker, Secretary, Employee Task: for each scenario Draw the inheritance hierarchy, showing which is the superclass Give the superclass two plausible fields which should be inherited by all subclasses For each subclass, add one other field specific to that subclass Code the classes in Java D1.9 Explain the need for different data types to represent data items. I read an excellent answer to this question on StackExchange. Here it is: 01010100 01110010 01110011 01110100 01101001 01110100 01110100 01100101 00100000 00100000 01100101 01111000 01100011 01110100 01100101 01110100 01101111 01110100 01100001 01101001 01110100 01100101 00100000 01100100 01101110 01110100 01110010 01100110 01110010 01100001 01101100 00100000 01100101 01100101 00100000 01100101 00100000 01110100 01100001 01101001 01100010 00100000 01100100 01110011 01101001 01101111 01100101 01101001 00100000 00000000 01101000 01100001 00100000 01110011 01101110 01101111 01101111 01101101 01100001 01101100 00100000 01101001 01100101 01100001 01101001 01100101 01101101 01110010 01110100 01101110 00101001 00100000 00100000 01100001 00100000 01101111 01100101 01101100 00100000 01110100 01111001 01100110 00100000 00100000 00100000 00100000 01110100 01101001 00100000 01100100 01101001 01110100 01101001 01101011 01101110 01100111 00100000 01101110 01101111 01100101 01101101 01110010 00100000 01100111 00100000 00100000 01100001 00100000 01101111 01110000 01110011 00101100 01101001 01101110 01111000 01100101 01100001 01100101 01110100 00100000 01101101 01010011 01110100 01101101 00100000 01110000 01101111 01101001 01101001 00100000 01100001 01100101 00110000 01011001 01110111 01101000 01101111 01010100 00100000 01101110 01101001 01100100 01110011 01110100 01110010 01100001 01100101 01110010 00100000 01101101 01100001 01101001 00100000 01110100 01110100 01101110 01101101 01100001 01110010 01110100 00100000 01101110 01100111 01110100 00100000 01101110 00100000 01101111 01111100 01100001 01101111 01100001 01100101 01100011 01110010 01100001 01101110 01101111 01110101 01110010 01100110 00110000 01100101 01101001 01101001 01101110 01101001 01110111 01100001 01101101 00100000 00100000 01100101 01100001 00100000 01110010 00100000 01110010 01100101 01110100 01110011 01110100 01110010 01101000 01110100 01100001 01100100 01101111 01100001 01101001 00100000 00100000 00100000 01110011 01110011 01110100 00100000 01101000 01110011 00100000 01110100 01101110 01101111 01100101 01110100 01110100 01101110 01101110 00100000 01101110 00110001 01110100 01101100 01110011 00101110 01101101 01101111 01110010 01100101 01100110 01101100 01100100 01101101 01110100 00100000 01100100 01100101 01110010 01101000 00100000 01101000 01100001 01100101 01111001 01110011 00100000 01100100 01101110 01110100 01110100 01110111 01110111 01101111 01101100 01101000 01100001 01100001 01101001 01101001 01111001 01110100 01101110 01110011 01101001 01101111 00100000 01100100 01100111 01101111 00110000 00100000 01101100 00100000 00100000 01100101 01110010 01111001 00100000 01100001 01101001 00100000 01110011 01101000 01110100 01100001 01100001 01110011 01100101 01100010 01100101 01101110 00100000 01100011 01110011 01110100 01110101 01110100 00100000 01101000 01101001 01101001 01110010 01100001 01100101 00100000 01110100 01101100 01110100 01110000 01100001 01110110 01100101 01101110 00100000 01110100 01100101 01110010 01110010 00110000 01101110 01101001 01100101 00100000 00100000 01101011 00101100 01110111 01101001 01101011 01110011 00100000 01110010 01101000 01111001 01110011 00100000 01110010 01100101 00100000 01110011 01100001 00100000 01101001 01101000 01100011 00101110 01101001 01100001 01101100 01110100 01110100 01110100 01110011 01100100 00100000 01111001 00100000 01100101 01101100 01100101 01101110 01100111 01110100 01101000 01110010 01100101 01110100 00110000 01101111 01101110 01100001 00100000 01110111 00100000 00100000 01101000 01110010 01100101 01101001 01110100 01101111 01100001 01110011 01101111 01110101 00100000 01100011 01101000 01101100 01110000 01110100 01110110 01100001 01110100 00100000 01110011 01110100 01101100 01101000 00100000 01101111 01100101 01100001 01110100 00100000 01101001 01110011 00100000 01110010 01110100 00100000 01101000 01100001 01110011 01100001 00100000 00110000 00100000 01100111 01110011 00001010 01101000 01100100 01100010 01100101 01101100 00100000 01101110 01101000 01110111 01101110 00100000 01101110 01110011 01110100 01100001 01110101 01100001 01110000 01111001 01100101 01110100 01101001 00100000 00100000 00100000 00100000 01101111 01101111 01110010 00100000 01110100 01101000 01110101 01110011 00101110 01110000 01110100 01100001 01110000 01100101 01110100 01110100 01110100 01110100 00110001 01101111 00100000 01101001 00001010 01100101 01101001 01110101 01101110 01111001 01100011 00100000 01100001 00101101 00100000 01101111 00100000 01100101 01101000 01110101 01101101 01110100 01110010 01110000 00100000 00100000 01110110 01000110 01101110 01101110 01110010 01110101 01100110 00100000 00110001 01100001 01100101 01101110 00100000 00100000 01110010 00100000 01110100 01101111 00100000 00100000 01100001 01100101 01101111 00100000 01101110 01110100 01100101 01010100 01101110 01110010 01110100 00100000 00100000 01110010 01110100 01110100 01100001 01110100 01100110 01110100 00100000 01100001 01110011 01100001 01100101 01101111 01100101 01100011 01110111 01101001 01101111 01100101 01101111 01100101 01110100 00100000 01110100 01110011 01110100 01111001 01100100 01110111 00100000 01101111 01100001 01101001 01101001 01110010 01101001 01101110 01110010 00100000 01101001 01100101 01101111 01110010 01101000 00100000 01100101 00100000 01110000 01110011 01100101 01100001 00100000 01110111 01101111 00100000 01101000 01100100 01101110 01100101 01101110 00100000 01110000 00100000 01101111 01101111 01110100 01110010 01100001 00100000 01100001 00100000 01101101 01101111 00100000 01111001 00100000 01100101 01101001 01010100 01100011 00100000 01101111 01101110 01100101 01110011 01100100 00100000 01110100 01101110 00100000 00100000 00100000 01100101 01110000 01100011 01101001 01110010 01101001 01100001 01101010 01110100 01100001 01101111 01110100 01100001 01100001 00100000 00100000 00100000 01100010 01110010 01101001 01100111 01110101 01111001 00100000 01110010 01101000 01100100 01110101 01100001 00100000 01100001 01110000 01100011 01110010 01110100 01101000 01100101 00110011 01101110 01110100 01110000 00100000 01100001 01110100 01110010 01110100 01110111 01100100 01110100 01110010 01100101 01110100 01110100 01101111 01101101 01110100 01101100 01101111 01111001 01101011 01111000 01110100 01110100 01110010 01110010 01100010 01101001 01101001 01101101 01101110 01101100 00100000 01101001 01101100 01111101 00100000 01110011 01100011 01110100 01101110 01100101 01100001 01110011 01101000 01100101 01110011 00110010 00100000 00100000 01110010 01100001 01100010 01101000 01100001 01101111 01101111 01101111 01110010 01100101 01101111 01101100 00100000 01100111 01110000 01101001 01100101 01100100 00100000 00100000 01101111 00100000 01100001 01100001 01100101 01110010 01101110 01100001 01110000 01101001 01100100 01101110 01101110 01111001 01101101 01110100 01101001 01101000 01110010 01100100 00100000 01101110 01110100 00100000 00100000 01110011 00101101 01101111 01101110 01100101 01100011 01101100 01100001 01101110 00100000 01110101 00100000 01100001 00100000 01110000 01111001 01110111 01110010 01101100 01101110 01110011 01100001 01101111 01101000 01110101 01110000 01110100 01110111 01110001 01100001 01100001 01110100 01101111 01110100 00100000 01101111 01110011 00100000 01100001 01101000 01101110 01101001 01100001 00100000 00101000 00100000 01100001 01100001 01101000 01101001 01100010 01100110 01010101 01110011 01110100 01100101 01101110 01110011 00100111 01101100 01100101 01101110 01110111 01101100 00100000 01100001 01100001 01100101 01000111 00101100 01111001 01101110 01101111 01100111 01110010 01111001 00100000 01110101 01101001 01110010 01100101 01110011 01101001 01101101 01101110 01110100 01100011 01101110 01101001 01100111 01101110 01101110 00110000 01110100 01101101 01101110 01101100 01110101 01101110 01101001 00100000 01101101 01100101 01110101 00100000 00100000 01101100 01100001 01100100 01110110 01110011 01100001 01100101 01101001 01110011 01101101 00100000 00100000 00100000 00100000 01100101 01110101 01101000 01101111 01110000 01100010 01101001 01101110 01111001 00100000 01100101 01110110 01100001 00101101 01100001 01100101 00100000 01110011 00100000 01100101 01110011 01110011 01100101 01101111 01100100 01101100 01101101 01100111 01110100 01100001 01100010 01101110 01100001 01101001 01110100 01100001 00100111 00100000 01100101 01101100 01110011 00100000 01101110 00100000 01110011 01110100 01110000 01110000 01100001 00101101 01110010 01110100 01100111 01100101 01101001 01110010 00100000 00100000 01110011 01110011 01100101 01101011 01100101 01101110 01110010 01100010 00100000 01110011 00100000 01101100 00100000 01111000 01110010 00101110 00100000 01100001 00100000 00100000 00100000 01100101 01110100 01101100 01110011 01101000 01110100 00101110 01100010 01101110 01100001 00100000 01100100 00100000 01100001 00100000 01100001 01110010 01110010 01110010 01101100 01110011 01001110 D1.9 Explain the need for different data types to represent data items. All data stored on a computer system is ultimately just sequences of bits, like 11010010 Nope. There are only bits. But computers can do sums with negative numbers and decimals, so there must be minus signs and decimal points too? So how do computers do it? Come to think of it, aren't you reading text on a computer right now? How can all data be just bits?? D1.9 Explain the need for different data types to represent data items. All data are just sequences of bits, but the way those bits are interpreted gives them different meanings. Go on… The bits I gave you earlier, 11010010, could mean 210, -46, "Ò" or even 2.942726775082115848939 83212491E-43, depending on how they are interpreted. So I guess it's pretty important to make it clear exactly which data type you're using! D1.9 Explain the need for different data types to represent data items. Opposite is one of lots of ways of encoding text on a computer It's a table of numbers and their corresponding characters Look back at the previous example and you will see from the table that 11010010 = 210 = "Ò" But where are the Korean characters, the Cyrillic characters, the Arabic characters?? This scheme uses 8 bits and therefore only encode for 28 different characters Modern systems, such as Unicode, use as many as 16 or 32 bits. 32 bits gives you 232 = 4,294,967,296 different possible characters! This is another reason we need to specify data types – they take up varying amounts of space D1.10 Describe how data items can be passed to and from actions as parameters. The guide states: "Parameters will be restricted to pass-by-value of one of the four types in D.1.6. Actions may return at most one data item." (Teacher note: That's lucky, because Java is exclusively pass-by-value.) We will look at three examples: Passing a primitive data type to a method and attempting to change the variable passed Passing an object reference to a method and attempting to change the object the reference points to Passing an object reference to a method and attempting to change the reference passed D1.10 Describe how data items can be passed to and from actions as parameters. Passing primitives We try to add one to i within the method addOneToThisInt but it doesn't work Outside the method, the value of i is unchanged This is because i itself is not passed to the method, only a copy of i's value We can change the copy as much as we like, but the original i doesn't get changed Analogy: You want access to an important document that is locked within my filing cabinet. I make a photocopy of it and give it to you. You can tear it up, burn it, whatever you like, but my copy is safe. (The way to change i's value is to return the changed variable, and assign the return value to i, as in returnThisIntWithOneAdded) D1.10 Describe how data items can be passed to and from actions as parameters. Passing object references This time we pass to the method a reference to an object and try to change the object The object's id gets changed, both inside the method and outside! Analogy: You want access to an important document that is locked within my filing cabinet. I give you the key to the filing cabinet. If you change the document, you have changed the only copy. Some people mistakenly think that this means that Java is both pass by value (primitives) and pass by reference (objects) See the next slide for the truth… D1.10 Describe how data items can be passed to and from actions as parameters. The truth about Java Like before we pass to the method a reference to an object, but this time we try to change the reference itself by making it point to a totally different object! This fails. The reference outside the method still points to the original object Analogy: You want access to an important document that is locked within my filing cabinet. I give you a copy of the key to the filing cabinet. If you change the document, you have changed the only copy, but if you try to re-grind the key, you have not changed my key. Hence, whether primitives are passed or object references are passed, Java is always pass by value. D1.10 Describe how data items can be passed to and from actions as parameters. This is an advanced point for teachers, that may help with fielding a difficult question from students… ←Huh?! Compare this with the "passing object references" slide String is an object type, but you can't change the object by passing its reference to a method!? This is because it is an immutable type Java provides a few immutable types for very common object types such as String and the primitive wrapper classes In fact, it is recommended by software design gurus that you should always make your classes immutable where possible Not providing any setter methods is one way of doing this! D1.10 Describe how data items can be passed to and from actions as parameters. This is an advanced point for teachers, that may help with fielding a difficult question from students… ←Huh?! Compare this with the "passing object references" slide String is an object type, but you can't change the object by passing its reference to a method!? This is because it is an immutable type Java provides a few immutable types for very common object types such as String and the primitive wrapper classes In fact, it is recommended by software design gurus that you should always make your classes immutable where possible Not providing any setter methods is one way of doing this! D2.1 Define the term encapsulation D2.4 Explain the advantages of encapsulation Encapsulation is the practice of hiding the inner design of an object data type in a class. In Java this is achieved by using the private keyword for fields and methods that should not be accessible outside the class. This is also known as "data hiding" It is used to separate implementation (how an object is built) from interface (how an object can be used) It allows users of the object to concentrate on what is important to them, without having to get involved with the complexities of how the object works. It also prevents other objects from accessing and possibly corrupting internal data. Finally, the interface/implementation decoupling helps to reduce dependencies because changes can be made to the implementation without necessitating changes to the interface. A car is a good real-world example. The details are kept hidden away under the hood, while the tools you need to drive the car are easily available. Implementation Interface D2.2 Define the term inheritance D2.5 Explain the advantages of inheritance One class (the subclass) can be programmed to inherit from another class (the superclass) The subclass automatically gets all of the fields and methods of the superclass (except ones explicitly declared as private) The subclass can override any of the fields and methods of the superclass by declaring its own version with the same name Inheritance forms an "is-a" relationship. For example, you might design a Car class to inherit from a Vehicle class because a car is a vehicle. Inheritance allows code reuse because you can create a new object type from an existing one; you don't need to write the code again. It also helps to avoid errors by reducing the number of times the same piece of code has to be written. In Java, inheritance is implemented using the extends keyword. Practice with inheritance hierarchies Sample Superclasses: Vehicle {Car, Bus, Lorry} Animal {…etc Employee RPGCharacter Shape Publication Subject Teacher Student Task: 1. Choose a superclass. 2. Identify three possible subclasses 3. Identify one variable and one method that belongs to the superclass 4. Identify one variable and one method for each of the subclasses The "is-a" test If you create an inheritance hierarchy e.g. class [Subclass] extends [Superclass], then it must make sense to say the sentence: "A [Subclass] is a [Superclass]" (e.g. "A square is a shape" makes sense.) If that sentence doesn't make sense for your example, then you haven't got an inheritance hierarchy. Which of these are valid inheritance hierarchies using the "is-a" test? class class class class class class Finch extends Bird Guitar extends Intrument Teacher extends School Player extends FootballTeam Beef extends Meat Actor extends Movie D2.3 Define the term polymorphism D2.6 Explain the advantages of polymorphism Polymorphism in object-oriented languages refers to the facility by which one object or function can exhibit different attributes and behaviours depending on the context. The guide states: "Actions have the same name but different parameter lists and processes." This seems to suggest that the IB are only interested in method overloading, which is compile-time or "static" polymorphism. Method overloading allows the same name to be used for more than one method. Java decides which method is the correct one to use depending on the type and number of arguments. This makes objects more robust because they can gracefully handle lots of types of input. It also simplifies the code that uses the object, because it doesn't have to explicitly deal with each different possible scenario. The object itself can do that. Compile-time polymorphism D2.3 Define the term polymorphism D2.6 Explain the advantages of polymorphism There is another type of polymorphism in Java called run-time or "dynamic" polymorphism. This type of polymorphism allows objects of a particular superclass to be treated as a homogeneous collection, while still exhibiting behaviours as specified in the heterogeneous subclass definitions This is particularly useful when processing lists of objects of an unknown or random subtype. The calling code can invoke the same method on each object in a collection, and those objects will respond appropriately depending on their type. Run-time polymorphism D2.7 Describe the advantages of libraries of objects. A library is a repository of code that can be imported into a project. Libraries mean that code doesn't need to be re-created by different programmers each time they develop some software. Library code is often provided by advanced programmers who know the language well and have optimized and tested it thoroughly. In this way, using library code improves performance and reliability of software. An example of library code is the Java API: http://docs.oracle.com/javase/7/docs/api/ D2.8 Describe the disadvantages of OOP D2.9 Discuss the use of programming teams Disadvantages of OOP Simple tasks can be overcomplicated by the use of OOP Key concepts such as inheritance, encapsulation and polymorphism can be difficult to grasp initially Programmers may be unfamiliar with the approach; there is a learning curve Programming in teams Allows specialisation in one area, e.g. testing, documentation Dependency reduction using techniques like encapsulation can mean that different programmers can work on different objects simultaneously without any danger of incompatibility Concurrent development like this reduces the time required to build new software Programmers working alone have to do everything serially and have to have expertise in all areas of software design and development D2.10 Explain the advantages of modularity in program development. Modules can mean classes, functions, or any other set of related code Facilitates collaboration. Different programmers/teams can work on different modules. Makes the system easier to understand. Promotes code reuse. Modules can be used in more than one system. Easier to test and debug because each module can be tested separately (see Unit testing) D3.1 Define the terms: class, identifier, primitive, instance variable, parameter variable, local variable • Class: Combination of data and operations that can be performed on that • data; specification of the data members and methods of the object. • Identifier: The name or label chosen by the programmer to represent a variable, method, class, data type or any other element defined within the program. • Primitive: a basic non-object data type built in to a language; in Java the primitives are byte, short, int, long, float, double, boolean, char • Instance Variable: a variable defined in a class of which each instantiated object has its own copy (cf class variable) • Parameter variable: the variable in the signature of a method that holds the value of the an argument passed to the method when it is called • Local variable: a variable that has local scope; a variable defined within a method that is not visible outside the method D3.2 Define the terms: method, accessor, mutator, constructor, signature, return value. • Method: a procedure defined within a class • Accessor: a public method that returns the value of a private instance variable. Used along with a mutator to implement encapsulation. Also "getter" because its name conventionally begins with "get", e.g. "getId" to return the private Id variable. • Mutator: a public method that allows the value of a private instance variable to be set by passing a parameter. Used along with an accessor to implement encapsulation. Also "setter" because its name conventionally begins with "set", e.g. "setId" to set the value of the private Id variable. • Constructor: a method with the same name as the class that executes when an object of the class is instantiated • Signature: the first line of a method, which includes the return type, the method name, and the parameter types and names • Return value: the value returned by a method's return statement D3.3 Define the terms: private, protected, public, extends, static • private: if a field or method is declared private then it cannot be accessed or called from outside the class; not even subclasses will inherit elements marked private • public: fields or methods marked public can be accessed or called from anywhere • protected: protected is between private and public; fields or methods marked as protected can be accessed within the class, by subclasses and by other classes within the same package, but not from outside the package • extends: the extends keyword establishes an inheritance relationship between classes, e.g. Cat extends Animal • static: fields or methods declared as static belong to the class itself, not to any particular instance of the class. When the value of a static field (aka class variable) is changed, it changes for all instances of that class. D3.4 Describe the uses of the primitive data types and the reference class string • The guide states: "In examination questions the primitive types will be limited to int, long, double, char and boolean." Using int and long • These are both integer types, which means they can store whole numbers only • They can store positive and negative values • ints generally use 32 bits, which means they have a maximum value of 216-1 ( 2,147,483,647) and a minimum value of -216 (- 2,147,483,648) • longs are 64 bits giving a range of -264 ( -9,223,372,036,854,775,808) to 264-1 (9,223,372,036,854,775,807), so they provide a wider range, but they take up more memory space • The following code gives x a value of 2 not 2.5. This chopping off of the decimal portion of a number is called truncation and it happens as a result of integer division: int x = 10/4; Just in case the guide is not quite accurate, there are also two other integer types: byte (8 bits) and short (16 bits). The choice between which type to use will be governed by the range of numbers you are likely to need in your program. D3.4 Describe the uses of the primitive data types and the reference class string • The guide states: "In examination questions the primitive types will be limited to int, long, double, char and boolean." Using double • double stands for double-precision floating point number • It is used to store fractional numbers (numbers with a decimal point) • An accurate description of the range of possible numbers that double can represent is well beyond the syllabus! • You have to be careful with doubles because sometimes they give very funny results: Just in case the guide is not quite accurate, there is also another floating point type, called float. It takes up less space than double, and therefore has a smaller range of possible values. D3.4 Describe the uses of the primitive data types and the reference class string • The guide states: "In examination questions the primitive types will be limited to int, long, double, char and boolean." Using char • A char can store a single character • It has 16 bits and so can store 216 different values, from 0 to 65,535 • This allows for internationalization of Java by supporting a large variety of character sets from different languages Using boolean • A boolean stores either true or false and can store nothing else • They are often used as flag variables to signal that some condition has become true, e.g. the end of an list has been reached Using String • Strings are object types in Java, not primitives • They store textual information • The String object has methods to make string handling easier, e.g. length(), charAt(), contains(), indexOf(), etc D3.5 Construct code to implement assessment statements D.3.1–D.3.4. Class Instance variables Local variables Constructor Return value Method signature Accessor methods Parameter variables Mutator methods D3.6 Construct code examples related to selection statements if (condition 1) { code 1 } else if (condition 2) { code 2 } else { code 3 } switch (int variable) { case 1: code1; break; case 2: code2; break; case 3: code3; // No break! case 4: code4; break; default: default code; break; } Java if block • If condition 1 evaluates to true, then code 1 executes. Otherwise, if condition 2 evaluates to true, then code 2 executes. Otherwise, code 3 executes. • Note that only one of code 1, code 2 or code 3 executes. That is the role of the else keyword. Java switch block • If the int variable is equal to 1, then then code1 executes. The break then causes execution to skip the rest of the switch block. • If the int variable is equal to 3, then code3 executes and because there is no break, code4 executes as well! • If the int variable is not 1, 2, 3, or 4, then only the default code executes. • Each of the cases, including the default code, is optional. D3.7 Construct code examples related to repetition statements while (x < 10){ output(x); x = x + 1; } do { output(x); x = x + 1; } while (x < 10) for (int x = 0; x < 10; x = x + 1) { output(x); } for (int x : Iterator) { output(x); } while loop • Continues to execute while the condition is true • Executes 0 or more times do while loop • continues to execute while the conditions is true • Executes 1 or more times for loop • Built-in counter that can be initialised to any value and which can be incremented by any value • Continues to execute while middle condition is true Enchanced for loop • Iterator can be any iterable object, such as an array or collection • The variable takes the value of each element of the collection, one after the other D3.8 Construct code examples related to static arrays int array[] = {2, 5, 4, 8, 6, 7, 1, 3}; arry[4] = 0; for (int i = 0; x < array.length; i = i + 1) { output(array[i]); } for (int i : array) { output(i); } • Declaration of an array literal • Direct access • Standard array traversals using a for loop and an enhanced for loop D3.9 Discuss the features of modern programming languages that enable internationalization Identifying culturally dependent data: Messages Labels on GUI components Online help Sounds Colors Graphics Icons Dates Times Numbers Currencies Measurements Phone numbers Honorifics and personal titles Postal addresses Page layouts Java provides a Locale object that facilitates internationalization 8-bit ASCII could only support 28 = 256 different characters, so different alphabets were not supported Unicode uses 16 bits to encode characters, and so supports 216 = 65536 characters D3.10 Discuss the ethical and moral obligations of programmers • A good list is provided by the Association of Computer Machinery, which is the US professional body for computer professionals: • http://www.acm.org/about/code-of-ethics • Another is provided by its British counterpart, the British Computer Society: • http://www.bcs.org/category/6030 • The Computer Ethics Institute provides the Ten Commandments of Computer Ethics • General areas to identify in exam questions are: • • • • • • Security: is data safe from unauthorised access? Privacy: how is personally identifiable data collected and stored? Plagiarism: presenting someone else's work as your own Piracy: copyright infringement Malware: hostile or intrusive software, including viruses Bugs: who is to blame for bugs in safety-critical systems, such as medical or nuclear reactor control systems? • The Open Source movement encourages software developers to release their source code for others to study and use. Open source licence conditions say that any changes or modifications to open source software must themselves be open source. The goals of the movement are: • Learning through sharing • Working cooperatively with like-minded people • Producing high-quality software HL only D4.1 Define the term recursion • Recursion is the process of a function calling itself • It can be used when the solution to a problem can be defined in terms of solutions to a smaller problems of the same type • For instance, n! = n × (n-1)! • Traditional examples are: • • • • • Fibonacci sequence Factorials Towers of Hanoi Binary search Binary tree insertions and traversals • Advantages of recursion: • Complex problems can be expressed elegantly and simply • Disadvantages of recursion: • Can take up large amounts of memory • Can be confusing to trace and bug-fix • It is generally considered wrong to use recursion if there is an iterative alternative that is just as simple and elegant, e.g. linked list traversal D4.2 Describe the application of recursive algorithms int factorial(int n) { if (n == 1) { return 1; } else { return n * factorial(n - 1); } } HL only "base case" recursive call • In the call factorial(5), the function returns the result of the calculation 5 x factorial(4). The factorial(4) call makes a call to factorial(3) and so on down to factorial(1). This is the base case of the recursive algorithm, and 1 is returned. The factorial(2) call can now calculate 2 x 1 = 2 and return the result to the factorial(3) call, which in turn returns the result of 3 x 2 = 6 to the factorial(4) call. The factorial(4) call returns the result of 4 x 6 = 24 to the original factorial(5) call, which can now go ahead and calculate 5 x 24 = 120, which is the correct result. • All recursive algorithms must have a base case, or they would keep calling themselves forever. HL only D4.3 Construct algorithms that use recursion • In addition to the factorial algorithm, here are some other famous recursive algorithms in Java Towers of Hanoi void hanoi(int n, int from, int to, int via){ if (n==0) { return; } else{ hanoi(n-1, from, via, to); System.out.println(count++ + ". Move a disc from " + from + " to " + to); hanoi(n-1, via, to, from); } } Binary search int binary_search(int A[], int key, int imin, int imax) { // calculate midpoint to cut set in half int imid = midpoint(imin, imax); // three-way comparison if (A[imid] > key) // key is in lower half of the list return binary_search(A, key, imin, imid-1); else if (A[imid] < key) // key is in upper half of the list return binary_search(A, key, imid+1, imax); else // key has been found return imid; } inOrder binary tree traversal void inOrder(Node n){ if(n == null) return; inOrder(n.left); print(n); inOrder(n.right); } Binary tree node insertion void insertNode(Node root, int data) { if (root == NULL) root = new Node(data); else if (data < root.getData()) insertNode(root.getLeft(), data); else insertNode(root.getRight(), data); } HL only D4.4 Trace recursive algorithms • Here is a trace of the binary_search algorithm provided in the last slide, for the call binary_search(A, 70, 0, 29) on the following array of 30 numbers. {2,5,9,12,17,22,24,31,34,38,42,44,48,50,53,54,57,62,65,69,70,73,76,77,78,82,84,87,89,93} • In each case you can see how the portion of the array that could contain the key is successively reduced. imax imin imid key array 29 0 15 70 {2,5,9,12,17,22,24,31,34,38,42,44,48,50,53,54,57,62,65,69,70,73,76,77,78,82,84,87,89,93} 29 16 23 70 {2,5,9,12,17,22,24,31,34,38,42,44,48,50,53,54,57,62,65,69,70,73,76,77,78,82,84,87,89,93} 22 16 19 70 {2,5,9,12,17,22,24,31,34,38,42,44,48,50,53,54,57,62,65,69,70,73,76,77,78,82,84,87,89,93} 22 20 21 70 {2,5,9,12,17,22,24,31,34,38,42,44,48,50,53,54,57,62,65,69,70,73,76,77,78,82,84,87,89,93} 20 20 20 70 {2,5,9,12,17,22,24,31,34,38,42,44,48,50,53,54,57,62,65,69,70,73,76,77,78,82,84,87,89,93} HL only D4.5 Define the term object reference • An object reference is an identifier through which a programmer can access the fields and methods of an object type. • It is different from the object itself, and is often called a pointer. • Object references can have a special value of null, which means they are not currently pointing to any object. • An attempt to access a field or method of a null object reference results in a NullPointerException. • For more information see the slides at the beginning of this presentation: • D1.2 Object references • D1.2 More on object references D4.6 Construct algorithms that use reference mechanisms. HL only • Most of the algorithms using "reference mechanisms" are likely to be associated with linked lists or binary trees. These will be covered in D4.84.10. D4.7 Identify the features of the abstract data type (ADT) List HL only • This is about using a List data structure, not coding it • You could get an exam question which tells you what operations a List supports, and then asks you to construct code that uses the List in some algorithm • What methods would you expect a List to have? • Here are some possibilities: • • • • • • • myList.isEmpty() myList.append(Object o) myList.prepend(Object o) myList.removeFirst() myList.removeLast() myList.find(Object o) myList.contains(Object o) Example: Each object in a list called items has two variables, a String name and an int number. The collection is ordered in ascending order of number. The list supports the following methods: isEmpty() getFirst() getNext() getNthObject(int n) hasNext() length() insertAtStart(Obj o) insertAtEnd(Obj o) insertAtN(int n, Obj o) Construct code using a for loop that prints the names of each object (4 marks) Construct code using a while loop that prints the names of each object (4 marks) Construct code that inserts an object o at the correct place in the list (6 marks) Construct code to sort the collection in descending order (2 marks) HL only D4.8 Describe applications of lists • Lists are very often used to create other standard data structures, like a stack or queue • Which of the standard methods that you might find in an abstract List object would you need to implement each of these? • Task: Construct a Stack class and a Queue class, complete with the standard methods that you would expect for those data structures, each of which contains a private List object that used to represent the stack/queue. • It is also important to remember that just because you don't know how a particular list method is implemented, that doesn't mean that it is an atomic operation (atomic = single, indivisible). • It still has to be implemented at some point! • e.g. java.util.ArrayList is a growable array, but it still has to resize itself from time to time, and that is always an expensive operation. D4.9 Construct algorithms using a static implementation of a list HL only • This means array algorithms • The only challenging algorithms are likely to be: • add a value in the middle of the array • remove a value from the middle of the array This is one possible algorithm for inserting a value at a specific place in an array Tasks: • Write the removeFromPlace method • Re-write both methods without using numElements. (Imagine that all elements in the populated part of the array are n > 0 and that all unpopulated elements are equal to zero.) D4.10 Construct list algorithms using object references • This means linked lists or binary trees • Linked list methods: • • • • • • • addAtHead addAtTail insert (in order) delete() list() isEmpty() isFull() Huh?? How would you implement an isFull() method for a linked list? Discuss. This is the insertInOrder algorithm. It's highly unlikely you will be asked to reproduce this in full, but you may need to code parts of it. • Compare with D4.8: What other methods would you need to code to be able to use your list to implement a stack or a queue? • Always check for an empty list before you remove, pop or dequeue! HL only HL only D4.11 Construct algorithms using the standard library collections included in JETS • JETS is on my blog https://retrosnob.files.wordpress.com/2012/08/jets.pdf • You are not expected to know everything about Java • JETS tells you what you should know (and what assumptions you can make) • This from the IB "Random Access Files and Sequential Files have no relevance to assessment statements in the guide but appear in JETS by mistake, most likely traces from the old syllabus. The guide overrules JETS. Feel free to ignore Random Access and Sequential files mentioned on JETS". • Make sure you are reasonably familiar with the list access methods: .add(E e), .add(int index, E element), .addFirst(E e), .addLast(E e), .clear(), .element(), .get(int index), .getFirst(), .getLast(), .remove(), .remove(int index), .removeFirst(), .removeLast(), .size(), .isEmpty() • And that you understand the basics of the Java Generics syntax e.g. LinkedList<String> list = new LinkedList<>(); D4.12 Trace algorithms using the implementations described in assessment statements D.4.9–D.4.11 HL only • This is self-explanatory. Not only must you be able to construct code with: • Static lists (arrays) • Dynamic lists (linked lists) • Built-in collections classes (e.g. ArrayList) • You must also be able to trace algorithms that use them D4.13 Explain the advantages of using library collections HL only • Libraries are collections of pre-written classes and functions that can be used by software developers as building blocks to write new computer programs • Code reuse. This means less effort, and less time to develop, therefore lower cost. • Code has been tested and optimized. This means that programs are less likely to contain errors and bugs. • The provide a layer of abstraction. The user of the library only needs to know the interface, not the internal implementation. D4.14 Outline the features of ADT’s stack, queue and binary tree HL only • These are covered in Topic 5 but the elements are repeated here: Stack Queue Binary Tree Description A last-in, first-out (LIFO) list. The next item to be removed from the stack is the last item to have been added. A first-in, first-out (FIFO) list. The next item to be removed is the first one to have been added. A collection of one or more linked nodes such that each node can link to 0, 1 or 2 nodes. The first node is known as the root, and each child node of the root is the root of its own subtree. Hence a binary tree is said to have a recursive structure. Methods push() pop() isEmpty() enqueue() dequeue() isEmpty() add() and delete() preOrderTraversal() inOrderTraversal() postOrderTraversal() Uses Compilers use a stack for parsing the syntax of expressions. Operating systems use queues to schedule requests by processes for CPU time. Binary trees are most often used as binary search trees, where their nodes are ordered in some way. Binary search trees provide linear access and direct access very efficiently, and they are easier to insert new nodes into than would be a sorted array. In a procedure call, the 'call stack' is used to keep track of parameters and return values and the location in memory to which code execution branches and returns. 'Buffers' are holding areas for information that is being passed from one process to another, e.g. In a command line OS, you write instructions to the computer instead of clicking the mouse. The computer only evaluates your command when you press Enter, not after every keystroke. The place where it temporarily stores what you've typed is called a keyboard buffer, and to keep the characters in order it is implemented as a queue. Routers stored their routing tables in binary trees. Mathematics software will store expressions in binary trees. D4.15 Explain the importance of style and naming conventions in code • • • • • • • Variables and methods: camelCase Classes: ProperCase Constants: UPPER_CASE_WITH_UNDERSCORE Encapsulation of instance variables Indenting code Meaningful variable names Avoiding potentially confusing syntax like: • a = b++ ? d++ - --c : c*=2 / --d/=2 • (Could you write this in a clearer way without altering the semantics?) • These are conventions; Java does NOT enforce these Why do we need conventions? • Code will almost certainly be maintained by someone who didn't write it • Conventions • Increase readability • Makes maintenance easier • Decrease the introduction of errors and bugs HL only