Monday, 15 November 2010

CS Chapter 9.5-END

5
Look up toString in the library documentation.
What are its parameters?
What is its return type?

 Without being overriden, the toString() method does not take any methods and returns a string consisting of a representation of the object. This can be called by almost any instance, given it's a subclass of the Object class.
6
.... You can easily try this out.
Create an object of class Video in your project, and then invoke the toString() method from the Object submenu in the object's popup menu.

 Done:
 I can't upload pictures for some reason, the buttons to upload just won't work, I'll show you the issue tomorrow.
7
The version of print() shown in Code 9.1 produces the output shown in text figure 9.9.
Reorder the staements in the method in your version of the DoME project so that it prints the details as shown in text Figure 9.10.

Done:  
8
Having to use a superclass call in print() is somewhat restrictive in the ways we can format the output, because it is dependent on the way the superclass formats its fields.
Make any necessary changes to the Item class and to the print() method of CD so that it produces the output shown in text Figure 9.11.
Any changes you make to the Item class should be visible only to its subclasses.
Hint: You used to use protected fields to do this.

 I had an issue with this, I received an error after the method got overused. I'll talk to you about it next class:
9
Implement a transporter room with inheritance in your version of the zuul project.
 N/A Skipped Ch.7
10
Discuss how inheritance could be used in the zuul project to implement a player and a monster class.
N/A
11
Could (or should) inheritance be used to create an inheritance relationship (super-, sub-, or sibling class) between a character in the game and an item?
 N/A
12
Assume you see the following lines of code:
Device dev = new Printer();
dev.getName();
Printer is a subclass of Device. Which of these classes must have a definition of method getName() for this code to compile?

 The Device class must have a definition of the method getName(), however, the Printer class may have overrided the method, in which case the definition of the getName() method that will be used is the one in the Printer class.
13
In the same situation as in the previous exercise, if both classes have an implementation of method getName(), which one will be executed?
 As explained above, the Printer's version of the getName() method will be executed if it was overrided.
14
Assume you write a class Student, which does not have a declared superclass. You do not write a toString() method.
Consider the following lines of code.
Student st = new Student();
String s = st.toString();
Will these lines compile?
What exactly will happen when you try to execute?

 There is no reason why it should not work, as the first instantiation line is of the same type, and the toString method, as defined in the Object class, is one of the inherited methods of the Student class as it is not a primitive class. These lines of code will assign the details of the st Student object to a string, s.
15
In the same situation as the previous exercise (class Student, no toString() method), will the following lines compile?
Why?
Student st = new Student();
System.out.println(st);


16
Assume your class Student overrides toString() so that it returns the student's name. You now have a list of students. Will the following code compile?
If not, why not?
If yes, what will it print?
Explain in detail what happens.
Iterator it = myList.iterator();
while (it.hasNext())
{
        System.out.println(it.next());
}

 Yes, it will  compile, my only worry is that it's not calling the toString() method, and instead is simply printing a list of Student's names. This is obvious as there is no reference here whatsoever to any toString() method.
17
Write a few lines of code that result in a situation where a variable x has the static type T and the dynamic type D.
 T x = new D();
D y = new D();
ArrayList list = new ArrayList <T> ();
list.add(x);
list.add(y);
return list;

Tuesday, 9 November 2010

Chapter 8 Test

a. Describe how you can use two different BankAccount  objects (acc1 and acc2) on the BlueJ workbench to transfer funds from one account to the other.

I will describe this using my code which does this sort of transfering:
    public void transferMoney(double amount, BankAccount from, BankAccount to)
    {
        from.withdraw(amount);
        to.deposit(amount);
    }

Essentially what this does, is it takes withdraws a certain amount from one BankAccount object and it deposts a certain amount in another, to act as though they transfered money.

b. Use the relationship between BankAccount class and GoldBankAccount class to describe how inheritance works in Java. As you write your description you should use the following terms in an appropriate way.
 The relationship between BankAccount and GoldBankAccount deals with inheritance, in which BankAccount is the superclass of GoldBankAccount, and GoldBankAccount is the subclass of BankAccount. In an inheritance hierarchy, the BankAccount class would therefore appear above the GoldBankAccount class. In the superclass constructor, the fields important to it, and GoldBankAccount are found. Therefore, there is no need to reuse those fields, or recreate them in the subtypes of the superclass, that would simply defeat the purpose of inheritance. Another feature of this inheritance relationship is that we can create a BankAccount Object and assign a subtype with subtype variables to it.
 
c. A Bank class would store all the accounts held by a bank. The data structure that holds these accounts is a single ArrayList. How is it that a single ArrayList can store objects of different types (BankAccount, and GoldBankAccount)?
It can store objects of type BankAccount which include all subtypes, such as GoldBankAccount. Therefore it can store them both.

d. Implement the Bank class to include a method that computes the total of all the balances held by the bank.
 Done:
import java.util.ArrayList;
/**
 * Write a description of class Bank here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Bank
{
    // instance variables - replace the example below with your own
    private ArrayList banks;

    /**
     * Constructor for objects of class Bank
     */
    public Bank()
    {
        banks = new ArrayList <BankAccount> ();
    }
   
    public void addBankAccount(BankAccount object)
    {
        banks.add(object);
    }
   
    public int amountOfBanks()
    {
        return banks.size();
    }
}


e. Why are are wrapper classes necessary in Java?
 Because otherwise we couldn't be able to use primitive types in ArrayLists, as ArrayLists can only hold objects, but int and boolean, for example, aren't necessarily objects. Therefore there are wrapper classes for those classes, so they can be used in ArrayLists.

For those of you who work quickly..

(I will finish this later)
Create two new classes: JuniorGoldAccount, which is a more restrictive version of the GoldAccount class, and PlatinumAccount, which offers even more advantages than the GoldAccount.

Test your classes and include the code in this document

Monday, 8 November 2010

CS Chapter 9: 9.1-9.4


1
Open your last version of the DoME project.
Remove the print() method from class Item and move it into the Video and CD classes.
Compile. What do you observe?

 There is a compilation error since the title field belongs to the Item class from which we moved the method.
2
In your DoME project, add a print() method in class Item again. For now write the method body with a single statement that prints out only the title. Then modify the print() methods in CD and Video so that the CD version prints out only the artist and the Video version prints only the director. This removes the other errors ecountered above.
You should now have a situation coressponding to figure 9.4 in the text, with print() methods in three classes. Compile your project. This design should work, if there are errors remove them.
Before executing, predict which of the print() methods will get called if you execute the Database list() method.
Try it out: Enter a CD and a video into the database and call the Database list() method. Which print() methods were executed?
Was your prediction correct?
Try to explain your observations.

 Prediction: When executing the database print method, it will use the specific CD and Video print methods which will print out only either the artist or director, since we've overloaded the method in the sub-classes.

My prediction was correct.
3
Modify your latest version of the DoME project to include the super call in the print() method.
Test it.
Does it behave as expected?
Do you see any problems with this solution?

 Yes it works,
no problems:

4
Change the format of the output so that it prints the string "CD: " or Video: " (depending on the type of item) in front of the details.
 Done:

Thursday, 4 November 2010

Chapter 8 8.7-End


7
Open the dome-v2 project.
Add a class for video games to the project.
Create some video game objects and test that all the methods work as expected.

 Done, here are the class' fields:

8
Order these items into an inheritance hierarchy: apple, ice cream, bread, fruit, food-item, cereal, orange, dessert, chocolate mousse, baguette.
 Done:

9
In what inheritance relationship might a touch pad and a mouse be?
 Computer Devices
10

 Rectangle would be the parent class of square, as a square is a rectangle, but a rectangle is not a square, simply that.
11
Assume we have four classes: Person, Student, Teacher & PhDStudent. Teacher and Student are both subclasses of Person. PhDStudent is a subclass of Student.
Which of the following assignments are legal and why?
Person p1 = new Student();
Person p2 = new PhDStudent();
PhDStudent phd1 = new Student();
Teacher t1 = new Person();
Student s1 = new PhDStudent();
s1 = p1;
s1 = p2;
p1 = s1;
t1 = s1;
s1= phd1;
phd1 = s1;
 a) legal
b) legal
e) legal
g) legal
h) legal
j) legal
k) legal

because sub-types can be assigned to super classes, or to their own class, but super classes can't be assigned to sub-classes, it's like saying a square gets new rectangle, it's preposterous.
12
Test your answers to the previous question by creating the classes mentioned in that exercise, and trying it out in BlueJ.
 Done, this is the set up i used:

13
What has to change in the Database class when another item subclass (for example class VideoGame) is added?
Why?

 Nothing, because VideoGame is an Item, and therefore Item will allow VideoGame to be added to the ArrayList of Database without further coding.
14
Use the documentation of the standard class libraries to find out about the inheritance hierarchy of the collection classes. Draw a diagram showing the hierarchy.

 Unable to find the section on standard class libraries.
15
Go back to the lab-classess project from chapter 1. Add instructors to the project. Use inheritance to avoid code duplication between students and instructors.
 I attempted to add some methods to the project as well but received some compiling errors:

16
Draw an inheritance hierarchy representing parts of a computer system (processor, memory, disk drive, CD drive, printer, scanner, keyboard, mouse, etc.)

17
Look at the code below. You have four classes (O,X,T and M) and a variable of each of these.
O o;
X x;
T t;
M m;
The following assignments are all legal.
m = t;
m = x;
o = t;
The following assignments are all illegal.
o = m;
o = x;
x = o;
What can you say about the relationships of these classes?
 They have no relationships, therefore it makes no sense whatsoever to assign them to one another.
18
Draw an inheritance hierarchy of AbstractList and all its (direct and indirect) subclasses, as they are defined in the Java standard library.

 Done:

Tuesday, 2 November 2010

Chapter 8 8.1-8.6


Barnes and Kolling Chapter Eight Questions
Barnes and Kolling Chapter Eight Questions


1
Open the project dome-v1. It contains the classes exactly as they were discussed in the text.
Create some CD objects and some video objects.
Create a database object.
Enter the CDs and videos into the database, and then list the database contents.

 Done, here's the printed terminal:

2
Try the following.
Create a CD object.
Enter it into the database.
List the database.
You see that the CD has no associated comment.
Add a comment to the CD object on the object bench (the one you entered into the database).
When you now list the database again, will the CD listed there have a comment attached?
Try it. Explain the behavior you observe.

 The comment part of the CD class is a field, and all the lsit() method does, in the database class, is print all the object fields.
3
Draw an inheritance hierarchy for the people in your place of study.
 Done:

4
Open the project dome-v2. This project contains a version of the DoME application rewritten to use inheritance, as described in the text.
*Note that the class diagram displays the inheritance relationship.
Open the source code of the Video class and remove the "extends Item" phrase. Close the editor.
What changes do you observe in the class diagram?
Add the "extends Item" phrase again.

 It won't compile, because the class relies on many of the super-class methods to function. Also, if it would compile, it would still lack all the methods it shares with the CD class that were put into the parent class.
5
Create a CD object.
Call some of its methods.
Can you call the inherited methods(for example setComment())?
What do you observe about the inherited methods?

 They work just as they do with the methods inside the class, it's as though there's no difference, only to select and call the method one must right click the object and go to a list of "inherited from Item" methods.
6
Set a breakpoint in the first line of the CD class's constructor.
Then create a CD object. When the debugger window pops up, use Step Into to step through the code.
Observe the instance fields and their initialization.
Describe your observations.

 When the instance fields get initialized the process goes into the Item class to find the code needed to initialize the fields, and returns the CD instance with the required information, the field value.

Sunday, 31 October 2010

Chapter 5 35-48


35
Implement the final changes discussed in the text in your own version of the program.

A:
Done it.
36
Add more word/response mappings into your application. You should copy some out of the solution provided and add some yourself.
A:
System.out.println("You might want to just change you computer, it seems to be at the peak of its life");
System.out.println("Sorry sir, but this is not a playground, you may want to use more formal language");
System.out.println("Your insulting, and you expect help from us?");
System.out.println("Do you really think it's my fault this is not working?");
System.out.println("Your computer seems to be disfunctional, I recommend you buy a new one.");
37
Sometimes two words (or variations of a word) are mapped to the same response. Deal with this by mapping synonyms or related expressions to the same string, so that you do not need multiple entries in the reponse map for the same response.
A:
Done it.
38
Identify multiple matching words in the user's input and respond with a more appropriate answer in that case.
A:
Done, I'm still unsure, however, of how many times a user should say the word in order for it to become the more detailed response. In all cases however, I set it to five.
39
When no word is recognized, use other words from the user's input to pick a well-fitting default response: for example words like "who","why, "how"
A:
Done it, I simply threw back a question at the user. For example, "Why is this?" would return the response I made, "Why shouldn't it?".
40
Use BlueJ's Generate Documentation function to generate documentation for your techSupport project.
Examine it. Is it accurate?
Is it complete?
Which parts are useful, which are not?
Can you find any errors in the documentation?
 A:
It's not so complete, because I haven't documented everything, but for the parts that do have a default message from Barnes and Kolling, it seems pretty detailed, and complete. I see the purpose of @param and @version @author now. I'm unable to find any errors however.
41
Find examaples of javadoc key symbols in the source code of the TechSupport project.
How do they influence the formatting of the documentation?
A:
If key symbols like @param, appear in the source code of a project they become categories in which the text following their appearance is the test that appears in the category.

42
Find out about and describe other javadoc key symbols.
One palce you can look is the online documentation of Sun Microsystems' java distribution. It contains a documnt called  javadoc - The Java API Documnentation Generator.
In this document the key symbols are called javadoc tags.
 A:
Although many tags appear, the essential ones in my opinion are:
@link which inserts a link to another file or project.
and @author which describes and includes a section on where the project has come from.
43
Properly document all classes in your version of the TechSupport project.
A:
Done it. I included @param where needed, as well as @return, which explain the parameters of each method and return where I explain the results of the method.
44
Create a BallDemo object and execute the drawDemo() and bounce() methods.
Then read the BallDemo source code.
Describe, in detail, how these methods work.
 A:
Essentially, this project, in both methods, creates a few objects that work together in that they move and wait for each other to move. For example, the rectangle moves, then lets the line be drawn, then moves again. This all happens extremely fast, and together creates a series of movements which combine.
45
Read the documentation of the Canvas class. Then answer the following questions in writing, including fragments of Java code.
How do you create a Canvas?
How do you make it visible?
How do you draw a line?
How can you erase something?
What is the difference between draw() and fill()?
What does wait do?
 A:
a) You initialize it with a title, and/or, and two measurements of width and height, and/or a background color. However, you can omit everything but the title, and start it as a default like that.
b) When you instantiate a Canvas object, the terminal will automatically appear.
c) Call the drawLine() method where two points must be given in order for it to calculate a slope.
d) Use the erase() method, but enter the shape's name if you want to only erase a given object.
e) draw() simply makes the shape visible on the canvas, but fill() fills up the shape with a certain color. For example you can have an "open" circle, and fill it up with the fill() method.
f) wait() makes the shape wait for a specified amount of seconds before continuing.
46
Experiment with Canvas operations by making changes to the drawDemo() method of BallDemo. Draw some more lines, shapes and text.
A:
Done it. There's a whole spectrum of possibilities, but I chose to make a rectangle and move it to +50 on x, make it wait, then move it +300 on x to make it sort of materialize, move, wait, then leave.
47
Draw a frame around the canvas by drawing a rectangle 20 pixels inside the window borders. Put this functionality into a method called drawFrame() in the BallDemo class.
A:
Done, I'm only worrying that maybe the shapes will remove the fill of the rectangle after we call the drawDemo method...
48
Improve your drawFrame() method to adapt automatically to the current canvas's size.
To do this, you need to find out how to make use of an object of class Dimension.
 A:
I'm having trouble getting this one to work, i'll confront you with it during the day.