Tuesday, March 13, 2012

More Unix

#!/bin/sh  /*this shows what to run with, eg bash, ksh, sh */


notes:
* don't leave spaces where there should be spaces, things won't work.

Unix notes Week 2

#todo create a blog for unix, or rename this one to cover subjects other than java
#todo find out how comments are stored in UNIX, is /*comment*/ acceptable

Week 2
Pattern matching
ls
amemo memo memoa memosally user.memo mem memo.0612 memorandum sallymemo


ls memo?   /*result must start with memo and have 1 unknown char*/
memoa


ls memo* /*result must start with memo and have none to many unknown char after*/
memo memoa memo.0621 memorandum memosally 


ls memo[ar]* /*result must start with memo and a or r, followed by one to many unknown char*/
memoa memorandum


Signals
^Z     Control+Z     Suspends the interactive job and controls returns to shell
$ bg                 Puts the last suspended process to the background
$ jobs               Lists all your jobs (processes) that are running in the background
$ kill [0-...]       Different kill codes, examples follow
$ kill 2             interrupt  

$ kill 9             sure kill (cannot be ignored) 
$ kill 15            terminate






Wednesday, June 8, 2011

Exam Revision

Object Orientation

Interrogative message - asks the target object to reveal something, e.g. what is the current balance of the savings account. The target object is obliged to respond to the sender
Informative message - tells the target object something of interest, e.g. stock levels have fallen below 200. The target object does not respond to the sender, however it may do something in response to the notification (e.g. order more stock)
Imperative message - requests the object to take some action on itself / another object / the environment around, e.g. asking an ATM object to dispense cash


The 'this' reference
The keyword 'this' refers to the object which is executing the statement at that point in time (i.e. self).
E.G in a constructor, 'this' refers to the object which is being constructed.


Object Relations

A link is a connection between object instances
An association is a connection between classes -  an association is an abstraction of all likely links.




Wrapper Classes

ArrayList class can only refer to a collection of object type - it cannot refer to a collection of a primitive type, e.g. int
The Wrapper Class exists to allow a primitive type variable to behave as if it is an object, e.g. converting itself to a different format, or passing it as a parameter to a method expecting an object.
Each primitive data type has a corresponding wrapper class. All classes are public final, i.e. they cannot be extended.

Auto boxing
Primitive type data is automatically converted to object type when required via the auto boxing process. The reverse process (i.e. obtaining a primitive value with the same value as the wrapper objects) is known as auto unboxing.
Auto boxing occurs when inserting primitive type data into an Arraylist, and auto unboxing occurs during access to the ArrayList.

Inheritance
  • Technique for reusing existing classes as the basis for defining new classes, which add additional behaviours, or which modify the existing behaviours of an additional class
  • The class used as the bases is the superclass
  • The class which extends the superclass is the subclass
  • e.g. Employee is the superclass, Programmer and Team Leader are the subclasses
  • Inheritance introduces a form of coupling, as the subclass is affected when the superclass is changed
Generalisation
Taking a group of classes, determining commonality, promoting commonality to form a superclass, which is a general form of the existing classes

Specialisation
Developing a new class based on an existing class, i.e. creating a special form of the existing class

Overriding Methods
Write a new implementation of a method defined by an ancestor class (superclass, or the superclass' superclass). Overriding is where the method has the same set and order of parameters as the ancestor class.

Polymorphism

The principle that behaviour can vary in response to a message being sent to an object through a reference variable, depending on the actual type of object which the variable is referring to at the moment the message is received.

e.g. in the bank system, until the program is run (compile time) and the user selects the bank account, the withdraw method may vary

A polymorphic variable is a reference variable which is capable of referring to objects of a variety of types. The restriction is that the types to which it may refer must be descendants of the class type used in the declaration e.g. BankAccount currentCustomerAccount;
i.e. only objects of type BankAccount or any of it's subclasses may be assigned to the variable

Protected Access Modifier

Things which are marked as protected are accessible to any class in the same hierarchy - i.e. all ancestors and subclasses

Exception Management

Check Exceptions - Invalid conditions outside the control of the program, such as user input
Unchecked Exceptions - Defects / bugs in the program, i.e. logic errors

Wednesday, March 30, 2011

Week 4 Tutorial marked

The week 4 tutorial was due today (see this entry for what was required)

I spent a decent amount of time of this tutorial, and I found implementing Date objects to be quite obtuse. My main struggle was how to find the number of days between the endDate and today. Google taught me that, although there wasn't a Date.subtract method, there was a Date.add method, and you can pass a negative date to subtract. Except that didn't really help me work out how many days that was.

In the end, I subtracted one Date from the other, and, as they are both stored in milliseconds, I divided by (1000 * 60 * 60 * 24) (milliseconds to seconds, seconds to minutes, minutes to hours, hours to days). Although not very elegant, it was the same as Eddie's solution, so correct.

I didn't get much satisfaction out of that. I want my solutions to be nicer than that. Oh well!

Anyway, I got 10/10 again, which is good. I'm hoping to get really good marks for the assessment and assignments, as I'm a bit worried that the exam is worth 60% overall.

Tuesday, March 29, 2011

Interfaces

Here's a UML diagram of this week's tutorial discussion:


public void test()
{
    System.out.println("Enter ID");
    int id = scanner.nextInt();
    Employee employee = findEmployeeById(id);
    displaySalary(employee);
}

public void displaySalary(Programmer programmer)
{
    System.out.println(programmer.calculateSalary());
}

public void displaySalary(TeamLeader teamLeader)
{
    System.out.println(teamLeader.calculateSalary());
}


I need  to change the test method as follows:

public void test()
{
    System.out.println("Enter ID");
    int id = scanner.nextInt();
    Employee employee = findEmployeeById(id);
    displaySalary(employee);
    if (employee instanceof Programmer)
      System.out.println ((Programmer)employee.calculateSalary());
    elseif (employee instanceof TeamLeader)
      System.out.println ((TeamLeader)employee.calculateSalary());
    elseif (employee instanceof Cleaner)
      System.out.println ((Cleaner)employee.calculateSalary());
}


This isn't very good, because it's not very scalable. Every time a new class is created, it will need to be extended.

This is when interface comes in handy. Very little goes in the interface, the implementation is specified in the classes that implement it.

public interface SalariedWorker
{
    double calculateSalary;
}

public class TeamLeader implements SalariedWorker
{
    public double calculateSalary()
    {
        return 100 * 100
    }
}

public class Programmer implements SalariedWorker
{
    public double calculateSalary()
    {
        return 50 * 50
    }
}


Now I need to change my test method to implement the interface

public void test()
{
    System.out.println("Enter ID");
    int id = scanner.nextInt();
    Employee employee = findEmployeeById(id);
    displaySalary(employee);
    if (employee instanceof SalariedWorker)
      displaySalary((SalariedWorker)employee);
    else System.out.println("The employee is not a salaried worker");
}


And that's how to use interfaces.

My thoughts:
This makes sense to me, it's a much nicer way to determine if the subclass has a method. I haven't used instanceof before, I was wondering how you check what type of subclass something is.

Monday, March 28, 2011

I has an audience

Apparently I has an audience now (and in order news, I'm talking like a lolcat):












Sure, it's not many, but given that this is my first attempt at blogging in a long time, it's nice to know someone's reading. Perhaps it's time for a System.out.println("Hello World!"); joke. Or perhaps that's just lame.

Sunday, March 27, 2011

Formatting Date objects

I'm creating dates for my assessment - storing the start date and end date for a contractor's employment.

To print out the date, must use the SimpleDateFormat class, which will format the date to make it more readable.


public String toString()
{
SimpleDateFormat dF = new SimpleDateFormat("dd/MM/yyyy");
String theEnrolledDate = dF.format(enrolledDate);

return super.toString()
+ "/nEnrolled Date: " + theEnrolledDate
}

I've been having some issues with passing a date into a constructor, but I re-read an email from my tutor and it makes sense now (thanks Eddie!)

Constructor:


public Student(Date enrolledDate)
{
this.name = null;
this.id = idCounter++;
this.enrolledDate= enrolledDate;
}


Creating an instance of Student:
Student s1 = new Student(new GregorianCalendar(2011, 0, 3).getTime());


Just need to put the dates in, and remember that month is counted from 0, not 1.

UPDATE
Make sure that the values are initilised. SimpleDateFormat does not work when the date is null. It spits exceptions that don't make sense.....

In other news, wine is helping me with my coding. Lets just hope I don't go over Ballmer's Peak. Where's a breathalyser when I need one?