CSCI 201 Introduction to Algorithm Design
home | homework index | labs index 
FALL 2006  

Defining Classes and Declaring Objects

[an error occurred while processing this directive]

After completing this lab, you will be able to:

  1. Write class definitions
  2. Create an instance of the class (declare objects)
  3. Recognize the difference among class definitions, objects, and members of the class.

NOTE: You can use classes Account and AccountTest from textbook as example (see p.92)

Defining a Class

A class definition consists of

The basic syntax is:

public class MyClass
{
    // variable declarations 

    // method declarations and definitions
} 

Defining a Method

Method declaration includes the type of the value returned by the method, the name of the method, and a parameter list (variable declarations separated by commas). A method declaration is always followed by the method body.

For example, here is the method cube:

public int cube (int n)
// This method returns cube of the n {
return n * n * n;
}

The keyword public is used to make the method usable outside the class. If instead the keyword private is used, then the method can only be used within the class. The type of the value returned by this method is int . The name of the method is cube. The only formal parameter is a int variable called n.

The body of method cube contains one statement, which is a return statement. In general, a return statement has the form:

return expression; 

Every method that returns a value must have at least one return statement. Of course, a method definition may have other statements as well. As soon as a return statement is executed, the execution of the method stops even if more statements follow the return statement. Remember that every method must appear within a class definition, i.e. inside the braces that enclose the class.

Invoking a Method

In order to invoke (call) a method, the user must provide the name of the method followed by a list of arguments separated by commas and enclosed in parentheses. Since there may exist many objects of the same class, the specific instance of the class that the method should be used with must also be specified.

The syntax for invoking a method is:

object_name.method_name( argument list );

For example:

MyClass object  = new MyClass();
object.cube (4); 

will return the value 64 if method cube from above is declared and defined in the class MyClass. An argument ( 4 in this case), sometimes called an actual parameter, is an expression that corresponds to a formal parameter in the method declaration (int n in this case).

However the value returned by the call will be lost, because it was not assigned to any variable. In order to keep the returned value above the code should be changed to

MyClass object  = new MyClass();
int result;
result = object.cube (4); 

will assign the value 64 to variable result.

Constructors

When we first instantiated the object instance using new, you may have noticed that we used method MyClass( ) - a constructor.

A constructor is a method that is invoked automatically when a new instance of a class is created. Constructors are used to initialize instance variables of the newly created object.

To write a constructor, you write a method that has no return type and whose method name is the same as the class name. Constructors may receive a collection of parameters which are copied into instance variables. These copies must be made. Otherwise, the parameter value will be lost when the constructor completes.

The constructor is "called" by using the Java keyword new as shown above.

Pretend we have a class called intHolder which looks like this:

public class intHolder {
  private int myInt;    //instance variable that stores the number

  public intHolder () { //default constructor
        setInt( 0);
  }
  
  public intHolder (int n) { //parameterized constructor
	setInt (n );
  }
    
  public int cube ( ){ // This method returns cube of the n 
        return t * t * myInt;
  } 
  public void setInt ( int n) { //assigns new value to instance variable myInt
	myInt = n;
  }
	  
  public int getInt ( ) { //obtains value of the instance variable myInt
        return myInt;
  }
  public void displayInt ( ) {
        System.out.println("number: " + myInt); //displays the value of the instance variable myInt
  }
}

Frequently, a class is defined with multiple constructors, in which case new will succeed if it finds a matching constructor. For example the following constructor, which gives myInt a default value of 0, would match new intHolder().

public intHolder () {
	setInt (0);
}	

You can  match new intHolder(3) by including the following parameterized constructor.

public intHolder (int n) {
	setInt (n );
}	

 

Your Assignment

  1. Create a NetBeans project. Under Categories select General, and under Projects select Java Application
  2. Project Name: date.
  3. Project Location is  yourid/csci/201/date
  4. Go to the Create Main Class field and change the class name from date.Main to date.
  5. Delete definition of the method main, which was generated by NetBeans.
    public static void main(String[] args) {
    // TODO code application logic here
    }
  6. Write the definition for a class named date that will contain data members and member functions that meet the criteria in the list below. The date class is used for inputting date.
    Use class intHolder as example.
    class date specification:
    • the integer instance variables (fields) named month, day, and year.
    • member function to set the day: setDay is void, has an int formal parameter int newDay, should be a public member, and assumes that the value provided is correct.
    • member function to set the year: setYear is void, has an int formal parameter int newYear, should be a public member, and assumes that the value provided is correct.
    • member function to set the month: setMonth is void, has an int formal parameter int newMonth, and should be a public member, and assumes that the value provided is correct.
    • member function getDay is int, has no formal parameters, and should be a public member. Returns day member.
    • member function getYear is int, has no formal parameters, and should be a public member. Returns year member.
    • member function getMonth is int, has no formal parameters, and should be a public member. Returns month member.
    • default constructor, that sets date to 01/01/2000. Hint: use methods setDay, setMonth, and setYear to set the date.
    • parameterized constructor, that initializes the three  instance variables. Hint: use methods setDay, setMonth, and setYear to set the date.
    • member functions displayDate is void, has no formal parameters, should be a public member, and displays date in format 12/04/2005. member. The method should display date in format: Date: 05/07/2005. Use if to display leading 0 or check http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html for zero-padded formatting.
      Example:
      		int x = 7;
      		System.out.printf("%d", x);  //displays 7
      		System.out.printf("%03d", x);  //displays 007
      

Show your code to the lab instructor.

Testing

Class date is not an application because it does not contain method main. To fix this problem we must either declare a separate class that contains a main method or place a main method in class date. In this lab we will use a separate class dateTest containing method main to test class date.

 

Checkpoint

Answer the questions below. You have to answer all questions correctly to see the rest of the lab.

How do you declare a method called display with one String parameter?
display
public display ( ) {  }
public void display ( String text) { }
public void display ( )

Assume we have a class named Account, and two reference variables defined as "Account account1;" and "Account account2;". Class Account has a displayBalance method. How do you call this method for account1?
displayBalance( )
Account.displayBalance( );
account1.displayBalance( );
account2.displayBalance( );

Which of the following can send parameter values to the constructor of class Account ?
Account account1 = Account("Ann Black", 100);
Account account1 = new Account("Ann Black", 100);
account1.Account("Ann Black", 100);
Account account1;

If an instance variable is defined as private, then we can use it
only in the class it is defined
only in the method it is defined
both in the class it is defined and in all other classes
only in other classes, but not in the class it is defined