Session 3 Lecture Notes for First Course in Java
course homepage      course calendar  

Tuesday, June 12

This session covers the reading in Day 2: A Taste of Object-Oriented Programming

[Note: For a simple introduction to object-oriented programming, see Object Technology: A Manager's Guide by David A. Taylor, 2nd ed., Addison-Wesley, 1998, ISBN 0-201-30994-7, $29.95.]

Review of Session 2  and Short Quiz

Object-Oriented Programming (OOP) basics

  • Objects
    • OOP versus Procedural Programming
    • embody a level of abstraction that is closer to everyday reality than are procedures
    • Advantages of object-oriented programming
      • Division of labor
      • Reusability/maintainability
    • Challenges of object-oriented programming
      • Need for up-front design
      • Overhead at compile-time and run-time
  • Classes
    • “Hello World” application uses a class
    • Real-world style objects: customer and book
  • Methods and Attributes
    • Methods: the “behavior” of an object
    • Attributes: the “state” of an object
    • Simple method calls, recursive calls
    • Example of methods for customer and book

Tower of Hanoi object-oriented design exercise

Homework Details

QUIZ

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

lecture 3

Object-Oriented Programming (OOP) basics

Object oriented programming (OOP) allows the designer(s) to think in terms analogous to those of the real world, because data (attributes) and behavior (methods) exist together in real world objects.

Examples: 

The "employee" object has 

Similarly, the "car" object has 

Object-Oriented Programming vs Procedural Programming:

C is a procedural programming language. In such a language you could make a car be a structure and pass it as a parameter to functions such as 'start_engine(car)'. 

Your code would be hard to maintain and reuse for a different type of car. For example, let us suppose that you decide later that you need to distinguish between manual transmission cars and automatic transmission cars. 

Therefore you would need two different structures to represents the two different types of cars (car_automatic versus car_manual), which would make it difficult to reuse the same 'start_engine' function because it would have to accomodate two different types of car parameters.

C++ and Java are Object-Oriented Programming Languages

To solve the same problem with object-oriented programming, you create a car template (or class), create an instance of the car class (a car object) and "extend" (specialize) the object of type car to support either a manual or an automatic transmission.

Objects embody a level of abstraction that is closer to everyday reality than are procedures. For example car lovers think in terms of 'Car' and see each instance of a car as both:

It is easier to think and design programs using objects because an object groups all these things together into one "object". This facilitates high level design, which is especially efficient for large projects with multiple programmers and multiple "components" that must come together into a systems that is larger, complex whole.  

Reusability is another plus of OOP. For example one group of programmers could write the code to control the Anti Lock Braking System and this core code could be re-used for different types of cars, even if the actual underlying hardware is different for a mini-van and for a sport convertible.  

OOP also introduces some new challenges. A good OOP architecture requires up-front design, and the design can be time-consuming. 

OOP is designed to make code reusable and extensible, therefore when you write your own objects you have to think about how other people might want to use it and extend it, which calls for a longer design phase. 

Only some people have the time and discipline to organize and plan (design) before they jump into coding. 

However, if you come up with a great design, it can save both you and others a great deal of time. Examples:

Syntax and implementation

Let us look at OOP at the code level.

Your object template is called a 'class', and each particular embodiment is an instance of this class. 

The following class example defines 4 attributes, 1 constructor and 3 methods.  
Class declaration syntax:  
<visibility> class <Class Name> 
{ 
  (<method declaration> | <attribute declaration>)* 
} 

Attributes:  

//  Define the Car class 
public class Car
{  // list of 4 attributes
   String  make  = "Porsche";
   String  model  = "914";
   int   year  = 1972; 
   boolean  isRunning  = false; 
   //  Constructor, which "initializes" the instance of the class 
   public Car(String theMake, String theModel, int theYear) 
   { 
        make  = theMake; 
        model  = theModel; 
        year  = theYear; 
   } 
  
   //  the first method starts the car 
   public void start() 
   { 
       if (isRunning() == false)  
   { 
       isRunning  = true; 
   } 
 } 
 
 //  the second method stops the car 
 public void stop() 
 { 
     if (isRunning()) 
     isRunning  = false; 
 } 
 
 // the third method returns whether or not the car is running 
 public boolean isRunning() 
 { 
     return isRunning; 
  }  
} 
//  you create the actual instance of Car outside of the class 
//  definition 

Methods:  

Note: the start and stop methods test for a condition by calling the isRunning() method and using the if keyword with different syntax.  

Keywords: return and void

A method can return one value. 
The keyword
void means that the method does not return a value. Unless you declare a method void, the method returns a value.

The return keyword means that execution returns the return value (if any) and also returns execution to the calling method. Here is an example of a return statement:

  return myValue;

Method declaration Syntax: 

To declare a Method in Java you have to be inside of a class.

  Constructor:  

The constructor is a special type of method because 

Notes:  

<visibility> <Class Name> ( <parameters list>)  

{  

  (<statements>)*  

}

Class instantiation:  

To create an actual instance from the class template, we use the keyword new followed by a call to the constructor. This call returns a reference to the instance.  

Syntax: <Class name> <variable name> = new <constructor>;

Example:

  //  by default this constructor creates Alex's car (Porsche 914 1972)  

Car  myCar  = new Car();  

//  this instantiation creates Thomas' vehicle

Car  yourCar  = new Car("Toyota", "Pickup", 1985);

Note: The word "new" is a Java keyword; neither Alex' nor Thomas' car are new except for the Java compiler when it creates them.

Method call:

A method call is the action invoking a method.

<visibility> <return type> <Method name> ( <parameters list>)
{
    (<statements>)*
}

A instance method applies a behavior to a specific object that has been instanciated.

A class method applies a behavior to a class. 
For example, a static variable

public class Car 
{

   // only instances of the class car can access this variable 
    private static int countOfCars; 

    public static int getCountOfCars() // class method
   {
        return countOfCars;
    }


    public Car() // constructor
   {
       countOfCars++; // increment the count of cars
   // each time we create a car
   }
}

The keyword this

The keyword this 

public class Car
{
    private String make = "Ferrari";
    private String model = "F-50";
    private String year = "2001";

    // the rest of the code ...

    // here are some javadoc comments 
    // (see another class for the explanation)
    /**
    * This method takes a Car as parameter and copies the values of the
   * different variables of the carToCopy
   * After this method call the current instance gets the same make,
   * model and year as the car passed as argument.
   * 
   * @param carToCopy the instance of Car which should be duplicated
   */
   public void copy(Car carToCopy)
  {
      // here we use the this keyword to access the instance variables
     this.make = carToCopy.make;
     this.model = carToCopy.model;
     //  The following call does not use this and is strictly equivalent to:
     // this.year = carToCopy.year; 
     // the this keyword is implicit
     year = carToCopy.year;  // year is implicitly this.year
   }
}


You can also use this to make a method call ('this.myMethod()' is equivalent to 'myMethod()' in the context of the current object).
The this keyword is rarely mandatory, and is for human readability, so that your reader (or yourself) knows right away on which instance the call is made.

Return values:

A Method can rerturn a value. The value returned can by any java type or class. Like we have seen in the example above: getCountOfCars() is declared as public int getCountOfCars() and therefore has to return an integer value).
To return a value from a method you use the 'return' keyword:

public int getMyNumber()
{
     return 6;
}


You can also do some sort of computation in the same line as the return:
public int getMultipliedNumber(int number)
{
    // this method will return the product of number and 3
   return number * 3;
}


Finally, you can also have method call(s) in the return statement:
public int getMyStuff()
{
    return (getMultipliedNumber(getMyNumber()) * 2);
}


The above return value will be computed as follows:
Step 1: getMyNumber returns 6;
Step 2: getMultipliedNumber(6) returns 18;
Step 3: 18 * 2 returns 36;
Step 4: return the value 36.

In Step 1, what you see is a nested method call, it means that you are calling a method by passing as an argument the return value of another method.

When you do not want to return any type of value, you should declare the method as void:
public void methodWithoutReturnValue() {}

Return and execution

The execution of a method is stopped immediately after the return statement, or after the computer crashes.
example:
public int method computeNumer()
{
   int value = 0;
   value = 3 * 4 * 5 * 6 * 7 * 8;
   return value;
   value = 0;
   return value;
}


The above code will not compile. The java compiler will stop with an error telling you that the statement 'value = 0;' is never reached. Because the method's execution ends after the first return statement.

Return statement can be optional

A return statement is not always necessary. 
If your method is declared as void, you are not required to have a return statement.
public void printHelloWorld()
{
    if (worldIsHappy)
{
    System.out.println("Happy, Happy, Joy! Joy!");
    // the following return prevents the printing of "Cheer up!"
   // if the world is happy, by stopping the execution of the
   // method
   return;
}
   System.out.println("Cheer up!");
   // This return is not necessary, if it is not there, the java compiler
   // will implicitly add it.
   return;

}

Recursion:

A recursive method is a method that calls itself.
For example, a method that calls itself upon the previous result of calling itself.
Factorial: 5! = 5 * 4 * 3 * 2 * 1. Note that factorial 0 = 1 by definition.

public class MathUtil
{
    /**
    * This method computes the factorial of a number, the algorithm
    * defined as: factorial(N) = N * (factorial(N-1) if N > 1,
    * if N is 1 or less, the value of the factorial is 1.
    * 
    * @param number the number for which to compute the factorial
     *  product.
    * @return returns the factorial of a given number. */
    public static int calculateFactorial(int number)
   {
       // this is the blocking test, this test is used to stop the
       // recursion, without this test, we would have an infinite
       // recursion.
       if (number > 1)
      {
          // we make a recursive call to compute the factorial
          return number * calculateFactorial(number -1);
       }
       else
      {
           return 1;
       }
  }
}


Notes:

Homework Details

  1. Become familiar with the Towers of Hanoi Game by experimenting with this applet: http://www.lhs.berkeley.edu/Java/Tower/Tower.html
  2. Note that

Assignment: Create stub-classes to implement a Tower's of Hanoi 'game' in an object-oriented fashion.
Deliverable: Source code for the class(es) you design to implement to contain the logic of the game.
Submit only the stub classes with their methods, and comments on what each method should do.
Do NOT fill the body of the methods. This is an exercise in design, not implementation.
Optional: Specify variables.

QUIZ

1.   True or False: An advantage of object-oriented programming is that you can save time because you can code directly, without having to spend time on design.

2.   True or False: A class is an instance of an object.

3.   True or False: An attribute is part of the “behavior” of an object?

4.   What defines the “scope” of a variable?

5.   What are three kinds of variables that each have a different scope?

6.   Name and define two kinds of visibility.

7.   What does a constructor do?

8.   Write a constructor for the class Car?

9.   True or False: The parameter list is different from the argument list.

10. True or False: The return value of a method cannot be passed as an argument to a method.

_________________________
course homepage      course calendar