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

21 April 2003

This lecture covers the reading in Chapter 6: Introducing Classes

agenda:
(1) review midterm;
(2) look at Calendar example;
(3) look at Manager subclass example;
(4) do Quiz

Overview of Object-Oriented Programming (more detail than day 1)

Class: its form and examples

Declaring Objects

Assign Object Reference Variables

Methods

Constructors

The this keyword

Garbage Collection

A Stack Class


Example of the Employee Class


Exception handling


Quiz

Homework Assignment


Overview of Object-Oriented Programming (more detail than day 1)

Let's look at an example of a class for showing the current day of the month.

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 versus 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 accommodate 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 in the case of a mini-van as opposed to a sport convertible.  

OOP also introduces some new challenges. A good OOP architecture requires up-front design, and the design phase, if careful and rigorous, 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 both of the following:

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 instance (or object) from the class (or template), we use the keyword new followed by a call to the constructor.

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

Result: The constructor constructs the object and returns a reference (variable name) for that newly created object.  

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.

Note: No, there is no corresponding "old" operator. The Java virtual machine periodically checks to see any objects are no longer available for use. If so, the JVM removes those objects. An object is no longer available for use if there is no longer any reference to that object.

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. (Note: a static variable is essentially a global 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
    }
}

Formal parameters   

 // Method definition has FORMAL PARAMETERS
    public int mult(int x, int y)
    {
       return x * y;
    }

    // Where the method mult is used, we pass in actual parameters
    int length = 10;
    int width = 5;
    int area = mult(length, width);

We use the term formal parameters to refer to the parameters in the definition of the method. In the example, x and y are the formal parameters. You can remember to call them ``formal'' because they are part of the method's definition, and you can think of a definition as being formal.

We use the term actual parameters to refer to variables in the method call, in this case length and width. They are called ``actual'' because they determine the actual values that are sent to the method.

You may have heard the term "argument" used, or just "parameter" (without specifying actual or formal). You can usually tell by the context which sort of parameter is being referred to.

Can the formal parameters names be identical with the actual parameters names?


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 return 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 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.

Step 1 is a nested method call because 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.
So far, we have been declaring public static void main(String[] args), and have not had return statements.


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 implicitly adds it.
   return;
}

Examples of a class

The output of this program is:
Volume is 6.0

Another example: this time there are two instances of the Box class. Each object exists separately from the other.

The output of this program is:
Volume is 6.0
Volume is 60.0

Note: The syntax for assigning a value to an instance variable is [object].[variable]= [value]


Class: its form and examples

Just as integer (int) and boolean are data types, so each object is an instance of a particular class.
The class to which an object belongs is its type.
When you define a class, you are essentially creating a custom data type.
(In this sense, object-oriented programming allows you to extend the programming language!)

Each an every object is an instance of a class. A class is a template for creating objects.

A class has attributes (properties) and behavior (methods).

The Unified Modeling Language (UML) is an industry-standard set of conventions for designing and analyzing classes.
Note in the diagram below the convention of putting the class name at the top, followed by a section for properties (nouns), and at the bottom a section for methods (verbs).

http://www.modelingstyle.info/classDiagram.html

(If you are interested in UML, see http://www.rational.com/uml/leaders/index.jsp)

What does the following code snippet do?

class Box {
   double width;
   double height;
   double depth;
}

In the class declaration, we create no object! There is only logic, no embodiment, no instance.

Because Java is a strongly-typed language, we need to declare the data type of each instance variable in a class.
And, each instance (each object) of the class has its own copy of the classes instance variables.
Think of it this way: if I have a blueprint for a house with three bedrooms and two bathrooms, each house I build with the blueprint will have three bedrooms and two bathrooms.

Declaring Objects

Box myBox; // creates an instance variable that holds the value null
mybox = new Box(); // calls the constructor and allocates memory to a new object (instance)
                   // that inherits the properties and methods of the class template

Note: The primitive data types, such as int, do not require the new operator because they are not objects. Indeed, they store their value directly.
However, a string is an object, yet you have declared String myString without having to use the new operator.
This is a convenience to you.

Assign Object Reference Variables

We saw already that two String objects are two separate objects, even if they hold the same value.

Comparing objects

This like saying:

Box b1 = new Box():
Box b2 = new Box();

On the other hand, if we say

Box b1 = new Box();
b2 = b1;

then b2 refers to the same single box object that b1 does.
Because there are two references to one object, either "handle" can modify the object they both point to.
What happens if we now say this:

Circle b2 = new Circle();

Do b2 and b1 still point to the same object, or has the most recent assignment pointed the two instance variables to different objects?
Do b2 and b2 still refer to objects of the same type or class?

Let's examine this example.

The output is:

Volume is 3000.0
Volume is 162.0

Methods

This example both defines a class and a method for that class.
Which instances of the class inherit the method?

What is going on in this example?

Let's examine the parameters to the method that sets the dimensions of the box.


Constructors

In this example, we use the object constructor (lines10-15) to assign hard-coded values to box objects.

Going a step further, here the constructor definition (lines 11-13) defines a signature that allows us to pass in actual values when we call the constructor to make objects (lines 25-26).
The constructor has a signature that facilitates making each box object different.


The this keyword

The this keyword refers to the object on which a method operates.

// A redundant use of this.
Box(double w, double h, double d) {
  this.width = w;
  this.height = h;
  this.depth = d;
}

The this can be implicit or explicit. In either case, the width property belongs to this box object that assigned "width" to have the value of w.
We call the w, h, and d, the formal parameters of the Box method, whereas width, height, and depth are the variables of the instance.

// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
  this.width = width;
  this.height = height;
  this.depth = depth;
}

Here, the this keyword solves the namespace collision caused by local variable hiding.
What that means is that the formal parameters of your method definition can have the same names as the instance variables of actual object, and yet we can keep the two straight.
The this keyword refers to this current instance (or object) as opposed to the method.

Garbage Collection

We have seen the new operator, but there is no old operator.
The JVM has a periodic daemon that cleans up unused memory.
The "garbage collector" considers that any object that no longer has a reference to it is "eligible" for garbage collection.
One advantage of Java is that you, as programmer, do not have the tedious tasks of memory management.
This is also an advantage to your end user, because it means less bugs and less memory leaks.
There is a protected finalize method to perform a custom operation before destroying an object, but this is too specialize for this introductory course.

A Stack Class

The output is:

Stack in mystack1:
9
8
7
6
5
4
3
2
1
0
Stack in mystack2:
19
18
17
16
15
14
13
12
11

Example of the Employee Class

The output is:

name=Carl Cracker,salary=78750.0,hireDay=Tue Dec 15 00:00:00 PST 1987
name=Harry Hacker,salary=52500.0,hireDay=Sun Oct 01 00:00:00 PDT 1989
name=Tony Tester,salary=42000.0,hireDay=Thu Mar 15 00:00:00 PST 1990

Now, let's look at inheritance. Note that line 88 refers to the superclass of Manager, which is Employee, with the keyword super.
We say that the subclass extends the superclass.


Error Handling

http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html


Quiz

  1. In what way is a class similar to a data type?
  2. In what way is a class different from a data type?
  3. What makes an instance variable different from some other type of variable?
  4. Write the code to declare an object called myObject.
  5. What does the constructor do?
  6. True or False: an object can inherit properties, but methods are strictly tied to the class that defines them.
  7. What is the purpose of the keyword "return"?
  8. What does the Stack class do?
  9. What is the advantage of creating an Employee class instead of putting its logic inside the main method?
  10. True or False: The variable names inside your various methods must all be unique.
  11. Explain what the garbage collector does. What does it look for? What does it do when it finds what it looks for?.
  12. What determines the scope of a method inside a class?
  13. What does the keyword super mean?
  14. What is the keyword to indicate that a class is a subclass of another class?

Homework Assignments

______________
course homepage      course calendar