Tuesday, July 05, 2005

Day 5, first OOP day and Day 6



Well... Last friday i started with the first OOP lesson.

Started out from C, a structure describing a Point


typedef struct Point {
  double x;
  double y;
};


and its use is as follows:


Point p;
p.x = 3; p.y = 4;
printf("(%lf,%lf)",p.x,p.y);


Then i convert both to Java


public class Point {
  double x;
  double y;
}


and in the main class:

Point p = new Point();
p.x = 3; p.y = 4;
System.out.println("(" + p.x + "," + p.y + ")");


Then i introduce them to the concept of methods by making the printing method built-in.


public class Point {
  double x;
  double y;

  void printPoint() {
    System.out.println("(" + x + "," + y + ")");
  }
}


And the corresponding modification to main:

Point p = new Point();
p.x = 3; p.y = 4;
p.printPoint();


I then show them the advantage of this... By having a lot of points declared, then have them have to change the ()'s into {}'s.

I try to teach them that calling a variable's method you are actually inside variable. I introduce them to concepts of class and object, attributes and methods at this point in time.

Since they are C programmers and are already familiar with functions, i get them to implement a double distanceToOrigin() method that returns how far the current point is to the origin.

The next concept i have to teach myself is the ability of a method to return a Point object via method Point midPoint(double otherX, double otherY). Then a short lesson on method overloading through a second method Point midPoint(Point anotherPoint).

Exercise for this is a Complex number implementation, something that represents Complex number a+bi were i is the sqrt of -1. Methods to be implemented are Complex add(Complex anotherC) and Complex times(Complex anotherC). Also an implementation of public String toString() (didnt tell them its special use yet) just so that they get used to using toString().

Common problems that i found with my students working on this is the problem of still using the variable used to reference this object inside the object.

i.e.

Complex c,d,e;
...
e = c.add(d);


and then inside the add method:

Complex add(Complex otherC) {
e.a = c.a + otherC.a //something like this
}


Another problem, which was kindof unexpected, was...

public String toString() {
  Complex result = new Complex();
  return result.a + " + " + result.b + "i";
}


Not sure how that happened, but around 4 pairs had this problem.

Anyway, i was too tired for Day 6 so i just gave them the period for their free-for-all ME.

0 Comments:

Post a Comment

<< Home