# OOP exam examples In this note I'm going to write a bit about example questions that I found and I taylormade for OOP to my students. You will find the solution to the questions in the spoiler section. ## Vampire administrator and bar Standard level exam. 45 marks. 1 hour. Very little time. A large organization of vampires with locations in different cities has taken an OOP approach in creating an administration program that manages all aspects of the organization (because Redondela the Thirsty Hacker said so). These aspects include: • The details of all the vampires including the address of their safe havens • The salaries of the administration vampires, familiar personnel • The monthly council meetings organizations 1) a) By using an example from the above scenario, distinguish between a class a and instantiation of a class. **[3]** :::spoiler Here we need to talk about the difference between a class, the blueprint and the object or instantiation of that class. The former represents the general element, or the _template_ and the later the specifics of one specimen. Possible examples: We can have the object Meeting that has the abstraction of all the meetings that the council has and one instantiation would be the meeting that is going to be held next mont. We can have the object Vampire that sets the template for all the Vampires and then we can have an instantiation of one specific vampire with their data of, for example Rendondela the Thirsty Hacker. For getting the 3 marks is important to be detailed with the explanation. For example: :::danger a class is vampire and an object is a vampire ::: The different modules in the program each open up a specific graphical user interface (GUI). Each GUI has a similar design (with all the blood symbols for vampires taste), but contains differences specific to each module. 1) b) By giving two examples, explain how the principles of inheritance can be incorporated into the design of this program. **[4]** :::spoiler In this question you have to give 2 examples that each is going to be marked up to 2 if the explanation is detailed enough. For example If we write a class for Council for the council meetings we can have another class with specific information and methods called SuperSecretCouncil that shares the rest with any generic Council We can have a GUI generic class with the elements that are common to all the GUI and then we can have loadingGUI or loginGUI, subclasses with different elements but that inherit the attributes and methods from GUI parent class. This allows to reduce the duplicated code Another example could be Payroll, that can have 2 subclasses depending if the person to pay is a Vampire or not a vampire. ::: 1) c) Describe how the use of libraries can facilitate the development of programs like this and help Rodoreda the thirsty Hacker **[3]** :::spoiler We need to define what is a library (usually 1 mark) and why is it useful to get the 2 other marks. For example: A library is a set of pre-written code that we can re-purpose so we can save time in not reinventing the wheel and usually is already tested. For example we can use a library for GUI since it is a common task for many programs. We can see an example of this here in arduino IDE: ![imagen](https://hackmd.io/_uploads/H1_wj0wbA.png) when we add this library "FastLED.h", the compiler can understand what is the object CRGB and we can use it without making ourselves that implementation, saving us time of development. ::: One of the departments of the Vampiric Council has a night bar. In this bar they can have fantasy beverages and also blood. ![imagen](https://hackmd.io/_uploads/ry9mLswZC.png) _wwdits reference_ This bar also needs to be manage the cost of the different elements purchased by the clients using an automatic system. Everytime a group of people start demanding one of the beverages, a Bill object is instanciated which will contain details of the items ordered. When the ghoul* barista takes the order from the clients, a BloodDrink or a RegularDrink is added to the Bill object as appropriate. *A ghoul in this context is a human hired by the vampires as a slave. Following you can see part of the class Bill and BloodDrink ```java! public class Bill { private BloodDrink[] bd = new BloodDrink[100]; private int bdCount; private const static double VAMPIRE_VAT = 0.30; // Blood beverages have an increment of 30% sale tax that goes to the vampire council private RegularDrink[] rd = new RegularDrink[100]; private int rdCount; private const static double VAT = 0.21; // 21 % sales tax added to all beverages to the human tax system public Bill() { bdCount = 0; rdCount = 0; } public BloodDrink getBloodDrink(int x) { return bd[x]; } // all other accessor and mutator methods are included // addBloodDrink() – this method adds a new BloodDrink object // addRegularDrink() – this method adds a new RegularDrink object public static double findPrice(Drink[] pl, String c) { //code missing } // calculateBill() – This method returns the bill (the total value of the items consumed for a particular table) } public class BloodDrink { private String itemCode; private int quantity; public BloodDrink(String x, int y) { itemCode = x; quantity = y; } // all accessor and mutator methods are included } ``` The RegularDrink class is defined in a similar way as BloodDrink. 2) a) Outline the implication of the use of the term `const` in the Bill class **[2]** :::spoiler Since this is 2 marks we need to add a little bit more that "cannot be changed". For example: It's written in the taxes attributes (VAT and VAMPIRE_VAT) so no other part of the code can change it's value. :::info This is not a common question in an IB exam. They usually ask for static, but I think is useful to talk about the difference between them. ::: ::: 2) b) Outline the implication of the use of the term `static` in the Bill class **[2]** :::spoiler We can answer in this case talking about attributes (VAT, VAMPIRE_VAT) or methods (findPrice) since there are both static. * Attributes A static attribute remains a shared value for all the instances of that class and can be accessed without an instance. * Method A static method (Also called class method) is a method that can be called without having an instantiation of that class and it's independent from the objects of that class. Typical examples: Math.random() or System.out.println() ::: 2) c) With reference to two examples from the classes described before, explain the benefits gained by the use of different data types. **[4]** :::spoiler Remember that we have to give 2 examples and each of them can give up to 2 marks. Remember that data types are int, String, bool, double, etc and also types of objects. Examples: * Having different data types allows to different operations being carried out. So you can multiply a number and not a String or a boolean * Double instead of int allows the use of decimal, something that might be interesting for prices that can have decimals. * Arrays allows the allocation of different values and be accessed or processed easily * Memory usage can be reduced, `int` uses less space than `double` ::: 2) d) Describe the purpose of this statement **[3]** ```java private RegularDrink[] rd = new RegularDrink[100]; ``` :::spoiler To get the 3 marks we need to say that it's **instanciating**, an **array of 100 elements** of RegularDrink that is **encapsulated** using the `private` modifier. ::: In the Bill class, the method addRegularDrink is passed a RegularDrink object as a parameter. This is the method called when the ghoul barista adds a new item to the Bill. 2) e) Construct the method addRegularDrink **[3]** :::spoiler First the answer ```java! public void addRegularDrink(RegularDrink d){ rd[rdcount] = d; rdcount = rdcount+1; } ``` Now how to write it. First the method signature so we understand where is it. We check in Bill class that is in that class, so we can have access to rd, rdcount, VAT and so on. Now we need to state if its public or private. By default the methods are public. Then we need to know that is the return type. We check again the statement and we don't see the return word anywhere, so we can assume that is void. Also we can think that this method is a kind of mutator because modifies something. These method usually have a return type of void. Finally we check the parameters. The statement says that an object of RegularDrink is passed. That's our parameter. Remember that in java we need the type AND a name for that. We can use d or whatever we want (we need to use it later) So we have the first line (and mark) ```java public void addRegularDrink(RegularDrink d) ``` Now some context that you need is that we're working with an array. So a Bill in this program has an array of RegularDrinks and an array of BloodDrinks. The idea is that in this array we have all the RegularDrinks or BloodDrinks, so when we add a RegularDrink we are adding one instance to that array. The unused elements of the array are just `null`. That array in the case of RegularDrink is called rd (look into the class). Since the array is fixed in length (100 that you can see in the class) we're using another variable to keep with the number of elements in the array. rdCount. So for doing that we need to put the Drink in the next empty spot of the array. What is the next spot that is empty in the array? ```java! rd[rdCount] ``` It will be the element that is rdCount since we're using 0-base index. ```java! public void addRegularDrink(RegularDrink d){ rd[rdcount] = d; } ``` So the other thing that we need to do is to update that count since we have _more_ elements (one more to be precise). Also if we left it like this the RegularDrink is going to be overwritten. So we use rdcount = rdcount +1 or rdcount ++ (also valid). So we finish with this. ```java! public void addRegularDrink(RegularDrink d){ rd[rdcount] = d; rdcount = rdcount+1; } ``` ::: warning **The order is important.** If we write rdcount++; before rd[rdcount] = d then we're going to have gaps in our array and probably some overwritting ::: 3) The global variable shift is declared as follows: ```java! Bill[] shift = new Bill[100]; ``` The indices in this array represent the different bills that are done during the night, so shift[1] corresponds to the second bill done in the night shift. The driver(main) class contains the following code: **Note:** You can assume that all appropriate accessor and mutator methods have been included in their respective classes. ```java= shift[0] = new Bill(); shift[1] = new Bill(); BloodDrink j = new BloodDrink("bd50", 2); BloodDrink g = new BloodDrink("bd47"", 1); RegularDrink r = new RegularDrink("d017", 4); shift[0].addBloodDrink(j); shift[0].addBloodDrink(g); shift[1].addRegularDrink(r); shift[1].addRegularDrink(new RegularDrink("d007",1)); System.out.println(shift[0].getBdCount()); System.out.println(Bill.getVampireVat()); System.out.println(shift[1].getRegularDrink(1).getItemCode()); ``` 3) a) State the output after the previous code is executed. **[3]** :::spoiler 2 0.30 "d007" Explanation: 2 is bdCount that is the counter of BloodDrink intantiations that we have in the first Bill (even if the total drinks are 3) 0.3 is a constant that we can have access from using directly the class d007 is the code of the 2nd drink of the 2 bill of the shift ::: 3) b) Construct statements, in code, that will print out the following: a. The number of total drinks intances (regular and blood) ordered by the third order of the shift **[1]** :::spoiler ```java System.out.println(shift[2].getbdCount()+shift[2].getrdCount()); ``` ::: b. The item code of the 2nd regular drink that was ordered by the 2 order of the shift. **[1]** :::spoiler ```java System.out.println(shift[1].getregularDrink(1).getItemCode()); ``` ::: The price of all the drinks are stored in an Drink class. The class is outlined bellow: ```java public class Drink { private String code; // item code private String name; // item name private double price; // unit price before tax // all accessor, mutator and constructor methods are included } ``` All of the objects in this class are held in the global array productList according to the following declaration: ```java Drink[] productList = new Drink[200]; ``` Note: The number of objects held in this array will change from week to week. The method findPrice(Drink[] pl, String c) in the Bill class looks up and returns the price of the item with code c. c) Construct the method findPrice(). You may assume that the item exists in the array. **[6]** :::spoiler 1) Where is this method? This method is in the Bill class. We can look it up and find it in this case we have the first line done for us. 2) Do the first line public static double findPrice(Drink[] pl, String c) From that line we know that is static, that returns a double and it takes a Drink array and a string. 3) Understanding what are the elements of that line The double is for price. The Drink array is the product list of all the possible drinks with their codes, names and prices. And the string c is the code that we're using. 4) Understanding what the method has to do. Describe if necessary. Read again the statement for this information. Some students don't remember that this information is just before the command "construct". There you can read the following > The method findPrice(Drink[] pl, String c) in the Bill class looks up and returns the price of the item with code c. Now we translate that to the correct order. Look up usually implies loop through, we have a condition (the code c) and when we find an element wit that condition is the one whose price (not the object itself in this case) we need to return. So what we have to do is loop through the array pl (product list), check if we find the code and, when we do (it's inevitable since we're told that the code is in the array) we return that value in a double. 5) Write code step by step To do the loop through the array we need to understand that we are looping through the array pl. We have several ways to do it: Using a for loop using the length of the array ```java for (int i = 0; i < pl.length; i++) { //blablabla } ``` Other option is to use a for loop knowing that pl is fixed to 200 elements even if the products may vary from one week to another. ```java for (int i = 0; i < 200; i++) { //blablabla } ``` We can also do a while loop with a similar condition (using length or 200) ```java int i = 0; while ( i < pl.length ) { //blablabla i++ } ``` Also we can use a while but instead of limiting ourselves with a length of the array we can use a flag variable that, if we found the element stops the loop. ```java int i = 0; boolean found = false; while ( !found ) { //!found means "NOT found" //blablabla i++ } ``` Now that we have the loop through the array we need to find the condition of the element that we're looking for. We need to check the code of the array. To do that we need to use *accessors* (getters) So, we need to use a getter to find the code of the current element of the product list (the array) and we need to compare to `c`, the code that we have as a parameter. To access to the Drink of the product list (pl) we need just to write `pl[i]` or instead the i the variable that we're using for the indexes. But we don't want all the object, we need only one value inside it: the code. For that we use the accessor `getCode()`. Finally we need to check if that is the same as the String c. For that we use the method equals `equals(c)` So we end with this ```java pl[i].getCode().equals(c)) ``` :::info **When to use equals()** Some markschemes make it mandatory and some don't. I suggest that if you remember how to use it use it for anything that is not a number nor a boolean (Strings, Objects mainly) ::: We put that in an if and we will have something similar to this: ```java Public static double findPrice (Drink[] pl, String c) { for (int i = 0; i < pl.length; i++) { if (pl[i].getCode().equals(c)) { //something something } } } ``` Now for that something something. We have also several ways to do this. We can either just return the element that we need or we can separate in some steps. In the case that we want to just return the element we use `return` with the access of the price of the Drink that we need. To access that we go to the current element `pl[i]` and we use the accessor method to access the price. We can return it right away or using a variable. This is the direct form: ```java Public static double findPrice (Drink[] pl, String c) { for (int i = 0; i < pl.length; i++) { if (pl[i].getCode().equals(c)) { return pl[i].getPrice(); } } } ``` If we keep it in a variable and we use it after the loop we need to break that loop. Also we need to initialize and define the variable beforehand. That's why you have the definition in the 3r line of the next snippet. ```java= Public static double findPrice (Drink[] pl, String c) { double price = 0.0; for (int i = 0; i < pl.length; i++) { if (pl[i].getCode().equals(c)) { price = pl[i].getPrice(); break; } } return price; } ``` :::info **Is it necessary to break the loop?** Usually is not but I have seen in some markschemes to give more points if you do. ::: ::: When a customer wishes to pay the bill, the calculateBill() method is called.If the bill was for the first order of the shift the following call would be made: ```java double finalBill = shift[0].calculateBill(Drink[] productList); ``` 3) d) Construct the calculateBill() method. You should make use of any previously defined methods. **[7]** :::spoiler 1) Where is this method? The method is in the class Bill. 2) Do the first line ```java public double calculateBill(Drink[] productListOfTheWeek) ``` To define that we need to check the first part of the exam an the usage where we see that an array of Drinks is passed as a paremeter. 3) Understanding what are the elements of that line double represents the total amount of money that the method is going to calculate _and return_ Drink[] is the array of Drinks that is the input. Is the list of possible beverages. In this case I name it productListOfTheWeek. We can go with pl or whatever name that we please, but we have to be consistent and we need to understand what does it represent. 4) Understanding what the method has to do. Describe if necessary. ::: 5) e) Construct a diagram showing the relationship between Bill, RegularDrink, BloodDrink and Drink classes. You don’t need to include the name of the attributes or methods of the classes. **[3]** :::spoiler TO-DO ![imagen](https://hackmd.io/_uploads/HJBEX1u-R.png) :::