CMPE 261 - Week 2

Anatomy of Java code-1

Anatomy of Java code-2

Class vs. object

  1. a template for objects: fields and methods which are not marked as static, and thus are non-static. Each object created from this class has their copy of such fields.
  2. fields and methods which are marked as static. These have nothing to do with objects, and there's only one copy of such fields which is in the class itself.
images
images

More on object creation: Constructor methods

Anatomy of Java code-3

Anatomy of Java code-4

Exercise

Write a simple class named Point to represent a point in two dimensional coordinate system. Add a method to compute distance of a point to another point. Add a Tester class and test assertions. You may use Math.sqrt(x) method to compute square-root \(\sqrt{x}\) when finding distance, and Math.pow(x,2) to compute square (or other powers) of a number.

Exercise Solution

    class Tester {
      public static void main(String[] args) {
        Point p1=new Point(5,5);
        Point p2=new Point(5,6);
        assert p1.distance(p2)==1;
      }
    }

    /** Represents a point in a 2-dimensional coordinate system */
    class Point {
      double x,y;

      Point(double x, double y) {
        this.x=x;
        this.y=y;
      }

      /** Returns distance between this point and given point */
      double distance(Point other) {
        return Math.sqrt(Math.pow(other.x-x, 2) + Math.pow(other.y-y, 2));
      }
    }

Anatomy of Java code -5: scopes and disambiguation

Reference vs primitive variables

images
images

The Garbage Collector

What happens if there are no more references to an object, i.e. if an object's address is lost? This happens for example:

    Point p=new Point(1,2);
    p=new Point(2,3);

The first object created above no longer has a Point variable holding its address. Such cases has been a huge problem in languages like C/C++ where the programmer is responsible for cleaning after himself/herself in such sitautions, which is often forgotten and cause memory leaks (cluttering of memory with such forgotten objects).

Java (and several other languages) have a garbage collector which keeps track of how many variables store references to an object: 2 in the previous example, 0 in the above example. When the count reaches 0 garbage collector destroys the object and claims the memory back to the usable memory pool of Java virtual machine (JVM), thus avoiding clutters. Garbage collector does not need to take immediate action, and usually invoked in moments when the JVM has a low process workload. Nevertheless, it frees the programmer from keeping track of memory usage, as in C/C++ case, which was quite error prone.

Reference variables: equality check

Case study of self references: Loves me not!

We want to write a class which represents a Person (e.g. their nick/name, gender, and age), and also who they love

    class Tester {
        public static void main(String[] args) {
            Person p1=new Person("Ali","male",20);
            Person p2=new Person("Ayşe","female",21);
            Person p3=new Person("Zehra","female",22);
            p1.setLove(p2);
            p2.setLove(p1);
            p3.setLove(p2);
            System.out.println(p1);
            System.out.println(p2);
            System.out.println(p3);
        }
    }

    /** Represents a person and who they love */
    class Person {
      String name, gender;
      int age;
      Person loves;

      Person(String name, String gender, int age) {
        assert gender=="male" || gender=="female" : "Invalid gender";
        this.name=name;
        this.age=age;
        loves=null;
        this.gender=gender;
      }

      void setLove(Person other) {
        loves=other;
      }

      public String toString() {
        if (loves==null)
          return String.format("%s (%s), loves noone",name,gender);
        else
          return String.format("%s (%s), loves %s",name,gender,loves.name);
      }
    }

Exercise

Add a method to Person class named lovesMeBack which returns whether the loved person loves back or not.

Preferably use enumerations for gender instead of strings (will reduce errors, and avoid checks!).

Exercise solution

    class Tester {
        public static void main(String[] args) {
            Person p1=new Person("Ali",Gender.MALE, 20);
            Person p2=new Person("Ayşe",Gender.FEMALE,21);
            Person p3=new Person("Zehra",Gender.FEMALE,22);
            p1.setLove(p2);
            p2.setLove(p1);
            p3.setLove(p1);
            System.out.println(p1);
            System.out.println(p2);
            System.out.println(p3);
            assert p1.lovesMeBack()==true;
            assert p3.lovesMeBack()==false;
        }
    }

    enum Gender {
      MALE, FEMALE;
    } 

    /** Represents a person and who they love */
    class Person {
      String name;
      int age;
      Gender gender;
      Person loves;

      Person(String name, Gender gender, int age) {
        this.name=name;
        this.age=age;
        loves=null;
        this.gender=gender;
      }

      void setLove(Person other) {
        loves=other;
      }

      boolean lovesMeBack() {
        return loves.loves==this;
      }

      public String toString() {
        if (loves==null)
          return String.format("%s (%s), loves noone",name,gender);
        else
          return String.format("%s (%s), loves %s",name,gender,loves.name);
      }
    }

Case study of mutual references: books and authors

Case study continued: constructor overloading

Case study continued: review of using mutable lists with ArrayList

Exercise:

Improve the Book class so that a book can have more than one author

HOME EXERCISES

For all the exercises below, try to implement a toString() method in order to test your programs visually.

  1. Improve the Author class so that an author object maintains a list of books by the author, hence it has an addBook method.
  2. Improve the Library class so that it can search for an author by its name, and for a book by its title.
  3. Write a Person class to implement a social network. A person has a name, a list of friends, and a method to add a new friend. Add a method which reports -on screen- which friendships are reciprocated, and which are not.
  4. Write a People class which can contain multiple people, thus has an addPerson method. Add a method to your class which reports average age of people it contains.