6: Classes and Methods

What We Will Cover


Continuations

Homework Questions?

Questions from last class?

What is the value returned by the following method?

int myMethod() {
    int value = 35;
    value += 10;
    return value + 5;
}
  1. 35
  2. 40
  3. 50
  4. 10

6.1: More About Methods

Objectives

At the end of the lesson the student will be able to:

  • Describe how void methods differ from methods that return a value
  • Trace method calls

6.1.1: Review of Methods

  • Writing methods is an important technique for breaking up your code into understandable pieces
  • Methods are declared by specifying a return type, name and a list of parameters
  • static double pow(double base, int exponent) {
        ...
    }
    
  • Values are passed to a method by putting values of a compatible type, in the same order, inside the parentheses of the method call
  • pow(2, 3);
  • Methods return a value using a return statement
  • return result;
  • Variables and parameters declared in a method can only be used within that method
  • When the method finishes executing, local variables disappear
  • Trying to use a local variable outside a method causes a compiler error

Program Example Containing Two Methods

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Power {
    public static void main(String[] args) {
        double value = pow(2, 3);
        System.out.println(value);
    }

    static double pow(double base, int exponent) {
        if (exponent == 0) {
            return 1;
        }
        int loopCounter = 1;
        double result = base;
        while (loopCounter < exponent) {
            result = result * base;
            loopCounter++;
        }
        return result;
    }
}

6.1.2: void methods

  • Recall that you code a void method whenever you do not want a method to return a value
  • In Java, void methods are defined like other methods that return a value
  • However, the keyword void replaces the type of the value returned
  • For example:
  • static void showResult(double result) {
        System.out.println("The result is: " + value);
        return;
    }
    
  • There are only two differences between definitions for void methods and other methods.
    • void return type
    • return statement is optional and does not specify a value if used
  • If no return type is specified, the method returns after executing the last statement
    • Why might you code a return statement if its use is optional?
  • When you call a void method you must code the call as a separate statement
  • A void method cannot be part of an expression
  • For example, look at the following method call
  • showResults(30);
  • This will cause the following to appear on the screen:
  • The results is 30.
    
  • Note that a void method does not return a value
  • Thus you cannot call a void method as part of a println() statement
  • System.out.println(showResult(30)); // not allowed
    
  • What possible value could be returned?

6.1.3: Methods Calling Methods

  • Methods may call other methods
  • Within the body of the method, you can code a method call
  • We are already doing this when main() calls another method
  • What does the following program display to the console?

Example of Methods Calling Methods

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class SquareCaller {
    public static void main(String[] args) {
        double number = 5;
        out("In main() the number is: " + number);
        double result = square(5);
        out("In main() the result is: " + result);
    }

    static double square(double number) {
        out("In square() the number is: " + number);
        double result = number * number;
        out("In square() the result is: " + result);
        return result;
    }

    static void out(String message) {
        System.out.println(message);
    }
}

6.1.4: Tracing a Method Call

  • When methods call methods, you need to follow the flow of execution
  • A method call transfers control to the first statement of the called method
  • When a return point is reached, control passes back to the point right after the method call
  • If the method call is part of an expression, the returned value is used in the expression
  • Let's trace the flow in the following code by line number:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class SquareCaller {
    public static void main(String[] args) {
        double number = 5;
        out("In main() the number is: " + number);
        double result = square(5);
        out("In main() the result is: " + result);
    }

    static double square(double number) {
        out("In square() the number is: " + number);
        double result = number * number;
        out("In square() the result is: " + result);
        return result;
    }

    static void out(String message) {
        System.out.println(message);
    }
}

6.1.5: Summary

  • You code a void return type when you do not want a method to return a value
  • For example:
  • static void showResult(double result) {
        System.out.println("The result is: " + value);
        return;
    }
    
  • The return statement is optional for void methods
  • When a void method executes the last statement, it automatically returns
  • If a return statement is coded for a void method, it does not include a return value
  • return;
  • Methods with a void return type cannot be called as part of an expression
  • Methods can call other methods, just like main() calls other methods

Check Yourself

  1. Why might you code a return statement if its use is optional?
  2. If no return type is specified, when does a void method return?
  3. Why cannot void methods be used in an expression?
  4. How do you code a method to call another method?

Exercise 6.1

Specifications

  1. Start a text file named exercise6.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 6.1
  4. In exercise6.txt, list the line numbers of the following program in the order they are processed.
  5. Do not bother to list lines containing just a closing curly brace (}) of a method definition.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class SquareCaller {
    public static void main(String[] args) {
        double number = 5;
        out("In main() the number is: " + number);
        double result = square(5);
        out("In main() the result is: " + result);
    }

    static double square(double number) {
        out("In square() the number is: " + number);
        double result = number * number;
        out("In square() the result is: " + result);
        return result;
    }

    static void out(String message) {
        System.out.println(message);
    }
}

6.2: Introduction to Object-Oriented Programming

Objectives

At the end of the lesson the student will be able to:

  • Describe what classes, objects, methods and instance variables are
  • Define a class and use it to create an object
  • Describe how to pass messages between objects
  • Call an object's method to perform a task
  • Describe how an object maintains state

6.2.1: About Classes and Objects

  • Everywhere you look in the real world you see objects
    • People
    • Animals
    • Plants
    • Buildings
    • Cars
  • Humans, including programmers, think in terms of objects
  • Humans learn about objects by studying their attributes and behaviors
  • Attributes are things like: size, shape, color and weight
  • Behaviors are what an object does, like:
    • A person walks, runs, crawls, talks and sits
    • A plant grows and wilts
    • A car accelerates, brakes and turns
  • Object-oriented programming (OOP) grew out of using software to model complex systems in the real world
    • Spread of disease in humans, animals and plants
    • Design of buildings or other large objects
    • Design of cars
    • Ecosystem simulation
    • Network routing
    • Weather prediction
  • Object-oriented design (OOD) models software like the way people study objects in the real world
  • It takes advantage of relationships where objects of a certain class, like buildings, have similar attributes and behaviors
  • OOD provides a natural and intuitive way to view software design
    • Once you get used to it
  • OOD models objects by describing their attributes and behaviors
  • It also models communication between objects
  • Just as people send messages to each other, software objects send messages
  • For example, a car object may receive a message to start its engine

6.2.2: Modeling Objects in Software

  • Let's use a simple analogy to help us understand classes and objects
  • Suppose you own a company and want to build a new type of car
  • You have engineers who develop blueprints or designs for the car
  • These blueprints describe all the attributes of the car, like:
    • color
    • number of wheels
    • top speed
  • We can use this analogy to introduce some of the OOP concepts
  • The blueprint is like a class in OOP
  • We create a design of the object by writing a class
  • A class describes the attributes of an object using instance variables
  • With class Car, we might have variables such as:
    • String color: the color of the car
    • int numWheels: the number of wheels
    • double speed: current speed of the car
  • Instance variables are said to hold the state of an object
  • A class also describes the behavior of an object using instance methods
  • For example, class Car might have a method like:
    • void setColor(String newColor): set the color of a car
    • void setSpeed(double newSpeed): set the speed of a car
  • However, a blueprint of a car is not a car
  • Before you can drive a car, a factory must construct the car
  • The construction factory uses the blueprints to make the car
  • Similarly, you must create an object of a class before you can use an object
  • After an object is built, you send messages to an object
  • How we send messages to a real car is we operate its controls
  • To send messages to a software car, we call its methods

6.2.3: Declaring a Class with a Method

  • Let us continue our analogy by writing a class for a car
  • We will keep it simple since we only want a simple model
  • All classes start with a statement declaring the class
  • For our first car class, we include a method to set the speed

Class Car

1
2
3
4
5
6
public class Car {
    public void setSpeed(double newSpeed) {
        System.out.println("Setting speed to "
            + newSpeed);
    }
}
  • The class declaration begins at line 1
  • The keyword public is an access modifier
    • For now we will just declare every class public
  • Every class declaration includes the keyword class followed by its name
  • In addition, ever class's body is enclosed in a pair of curly braces
  • Note that our class does not have a main() method, unlike other classes be have built so far
  • We still need a main() method for every application
  • However, we will put the main() method in a different class

Instance Method

  • The method declaration begins at line 2 with the keyword public
    • This indicates that the method is "available to the public"
    • This means that the method can be called from the outside of the class
  • After the keyword public is the method return type, name and a pair or parenthesis
  • In addition, ever method's body is enclosed in a pair of curly braces
  • The body of the method contains the statements that perform the method's tasks
  • Note that the keyword static is missing from the method declaration
  • The absence of the keyword static means that this is an instance method

6.2.4: Instantiating an Object and Calling a Method

  • Now we would like to use our Car in an application
  • Every Java application must have a main() method
  • Since our class Car does not have a main() method, it is not an application
  • If we were to try to execute the Car class, we would get an error message

Exception in thread "main" java.lang.NoClassDefFoundError: Car

  • To create our application, we need to either:
    1. Add a main() method to Car, or
    2. Add another class with a main() method to our application
  • To get used to large applications with many classes, we will write a second class with a main() method

Class CarTest

1
2
3
4
5
6
public class CarTest {
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.setSpeed(60);
    }
}
  • Class CarTest contains the main() method that begins our application's execution
  • Any class that contains a main() method can be used to control an application
  • The CarTest class contains only a main() method
    • Which is typical of many classes that begin an application's execution

Instantiating an Object

  • To use a Java class, you usually start by creating an object of the class
    • Also known as creating an instance of the class
  • There are two steps to creating an object:
    1. Code a variable to store the object
    2. Create the object using the new operator and assign it to the variable
  • To code the variable, you write the class name followed by an identifier
  • Car myCar = new Car();

Calling an Instance Method (Sending a Message)

  • In our application, we want to call the setSpeed() method
  • To call a method, you use the object name, a dot (period), the method name and a set of parenthesis
  • myCar.setSpeed(60);
  • When we call the method, we are sending a message to myCar to "set the speed"
    • In this example, we are setting the speed to 60

6.2.5: Declaring Instance Variables

  • When you send a message to an object, you often need to store some data sent as part of the message
  • Instance variables store the attributes of an object
    • Instance variables are also known as fields
  • Each object maintains its own copy of these variables
  • To continue our analogy, we will update our Car and CarTest classes

Class Car2

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Car2 {
    private double speed;

    public void setSpeed(double newSpeed) {
        speed = newSpeed;
        System.out.println("Setting speed to "
            + newSpeed);
    }

    public double getSpeed() {
        return speed;
    }
}
  • The instance variable is declared on line 2 and is named speed
  • private double speed;
  • Instance variables are declared inside a class declaration but outside the bodies of the class's methods
  • The keyword private means that the instance variable is not accessible outside the class
  • Most instance variables are declared private
    • Declaring an instance variable as private is known as data hiding
    • We will discuss why this is done later
  • To make use of an instance variable, we use an instance method that manipulates the variable
  • In our Car2 class, we have two such instance methods
    • Method setColor() will set or change the color of a Car2 object
    • Method getColor() will return the color of a Car2 object

Class CarTest2

1
2
3
4
5
6
7
8
public class CarTest2 {
    public static void main(String[] args) {
        Car2 myCar = new Car2();
        myCar.setSpeed(60);
        System.out.print("The speed of myCar is ");
        System.out.println(myCar.getSpeed());
    }
}
  • Class CarTest2 instantiates a Car2 object on line 3
  • On line 4, the myCar.setSpeed() method is called to set the speed of the car to 60
  • On line 6, the myCar.getSpeed() method is called to get the current speed of myCar

6.2.6: Summary

  • In object-oriented programming, objects are modeled after real-world objects
  • Object-oriented design (OOD) takes advantage of relationships where objects of a certain class, like cars, have similar attributes and behaviors
  • In object-oriented programming (OOP), we create a "blueprint" of an object by writing a class
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    public class Car2 {
        private double speed;
    
        public void setSpeed(double newSpeed) {
            speed = newSpeed;
            System.out.println("Setting speed to "
                + newSpeed);
        }
    
        public double getSpeed() {
            return speed;
        }
    }
    
  • Just like a blueprint is not a car, a class is not an object
  • Before we can use an object, we must create (instantiate) an object from the class
  • There are two steps to creating an object:
    1. Code a variable to store the object
    2. Create the object using the new operator and assign it to the variable
  • For example:
  • Car2 myCar = new Car2();
  • One you create an object, you can "pass it a message" by calling its methods
  • myCar.setSpeed(60);
  • Classes usually have methods that manipulate the attributes that belong to an object of the class
  • Instance variables (fields) store the attributes of an object
  • Each object maintains its own copy of these variables
  • Instance variables are declared inside a class declaration but outside the bodies of the class's methods
  • Most instance variables are declared with the access modifier private
  • private double speed;
  • Since the private modifier prevents access outside an object of the class, you must use the instance methods of the class to access an instance variable
  • We will discuss why this is done in the next section

Check Yourself

  1. What is a class?
  2. What is an object?
  3. What is the difference between a class and an object?
  4. What is the syntax for declaring a class?
  5. How do you create an object from a class?
  6. How do you pass a message from one object to another?
  7. How do you call an object's method?
  8. How does an object maintain state (remember its current settings)?

Exercise 6.2

Specifications

  1. Label this exercise: Exercise 6.2
  2. In exercise6.txt, list the class name and line number for the statements of CarTest2 and Car2 (shown below) in the order of their execution like this
  3. CartTest2: 2
               3
               4
    Car2: 4
    (finish listing here)
    
1
2
3
4
5
6
7
8
public class CarTest2 {
    public static void main(String[] args) {
        Car2 myCar = new Car2();
        myCar.setSpeed(60);
        System.out.print("The speed of myCar is ");
        System.out.println(myCar.getSpeed());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Car2 {
    private double speed;

    public void setSpeed(double newSpeed) {
        speed = newSpeed;
        System.out.println("Setting speed to "
            + newSpeed);
    }

    public double getSpeed() {
        return speed;
    }
}

6.3: Coding Classes to Define Objects

Objectives

At the end of the lesson the student will be able to:

  • Describe encapsulation and data hiding
  • Design classes that create objects
  • Code instance variables and instance methods of classes

6.3.1: Encapsulation and Data Hiding

  • As programs become larger, you need to change the way you work on them
  • Large programs usually have teams of people who work on them
    • One or two software engineers may work on the user interface
    • Another two or three may work on the logic of the application and various features
    • Another may work on data storage and retrieval
  • When many programmers work together, you need to take special care to protect the data of the application
  • For instance, two or three people may work on code to retrieve data from a database, make some computation and then display if on a screen
  • Unless the programmers take care, they may accidentally store incorrect values in the variables
  • These incorrect values show up as "strange bugs" that creep into the program
  • Object-oriented programs provide two important ways to help protect and control program data:
    • Encapsulation
    • Data hiding

Encapsulation

    Encapsulation: inclusion of a number of items into a single unit

  • Objects allow you to group many variables together in a program
  • This allows you to process the values and move them around together in your program
  • If the groupings are logically related, then you can more easily keep track of what is happening with the data
  • For example, we can keep all the data about a car inside one object
  • In addition to data, objects allow you to add methods to the groupings of variables
  • The idea is to add methods that work on the group of data
  • Thus, methods like setting the speed or amount of fuel in a car are grouped into the class that describes a car

Data Hiding

    Data hiding: restricting a program from directly accessing the data stored in a class

  • If you want to prevent a program from setting wrong values in the variables of an object, you need to check it first
  • To accomplish this, you "hide" the data by preventing assignment to the variables outside the object
  • Instead, you write methods to set new values in the variables
  • In these methods, you check the data to ensure the values are valid
  • These methods for setting and retrieving data are known as an object's interface

6.3.2: Defining Classes

  • Let us look at how to define classes using encapsulation and data hiding
  • Basic Syntax
  • [accessModifier] class ClassName {
        // body of the class
    }
    
  • The access modifier is optional but you should always use public for now
    • The public access modifier means all other classes can use this class
    • Later on we will discuss why you might chose another modifier
  • Also notice as we proceed that classes contain three general sections:
    • Instance variables
    • Instance methods
    • Constructors
  • We will look at instance variables and methods first
  • Later on we will look at constructors

For Example

  • The following is the code for a class named Product
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Product {
    // Instance variables
    private String name;
    private double price;

    // Instance methods
    public void setName(String newName) {
        if (newName == null || newName.length() == 0) {
            name = "Unknown";
        } else {
            name = newName;
        }
    }

    public String getName() {
        return name;
    }

    public void setPrice(double newPrice) {
        if (newPrice > 0.0) {
            price = newPrice;
        } else {
            price = 0.0;
        }
    }

    public double getPrice() {
        return price;
    }

    public String toString() {
        return "The product is: " + name
            + " and the price is: " + price;
    }
}
  • Here is a class to test it
1
2
3
4
5
6
7
8
public class ProductTest {
    public static void main(String[] args) {
        Product milk = new Product();
        milk.setName("Milk");
        milk.setPrice(3.95);
        System.out.println(milk.toString());
    }
}

Access Modifiers and Data Hiding

  • Note the keywords private and public in front of the method headings and variable names
  • These are called access modifiers or visibility modifiers
    • private: can only be accessed by member methods of this class
    • public: can be accessed by member methods of any class
  • Setting private accessibility for all data is a good design practice
  • Protects data by controlling access only through the public methods
  • Allows us to change how data may be stored at some future time
    • Without affecting code outside the class

Programming Style: Class Naming Conventions

  • Use nouns to name classes -- they represent objects
  • Start class names with a capital letter
  • Capital letter differentiates classes from methods and variables

6.3.3: Instance Variables

  • We now look at instance variables in more detail
  • You use instance variables to store the attributes (data) of an object
  • Each object has its own copy of these variables
  • The program reserves space for each variable when the new operator executes
  • Syntax for declaring instance variables:
  • [accessModifier] type variableName
  • For now, use the private access modifier for all instance variables
  • The type can be any primitive type or class name
  • Note that you declare instance variables outside of any method
  • This allows you to access an instance variable from any instance method of the object

Example of Instance Variables

    public class Product {
        // Instance variables
        private String name;
        private double price;
    ...
    }
    

Default Values

  • The compiler will initialize all instance variables to default values as follows:
    • Integer (byte, short, int, long): 0
    • Floating-point (float, double): 0.0
    • Character (char): '\u0000'
    • Boolean: false
    • Objects: null
  • Optionally, you can code an initial value for instance variables
  • For instance:
  • private String name = "NONE";
    private double price = -1.0;
    

About null

  • The keyword null is a special value that can be assigned to any class type
  • It means that no objects has been assigned yet

6.3.4: Instance Methods

  • Instance methods define the operations that can occur on an object
  • Performing these operations is sometimes referred to as passing messages
  • Objects use methods to pass messages to each other
  • The syntax for declaring instance methods:
  • [accessModifier] returnType methodName(parameter list) {
        // statements of the method
    }
    
  • Most of the time, you should declare methods public
  • However, if you want to prevent other classes from using a method, declare it private

Set Methods

  • When variables are declared private, you may still need to modify them
  • You use public methods to allow modification of the data
  • Methods of this type are called set methods (a.k.a. mutator methods)
  • The convention for naming these methods is to use the name of the variable with the word set prepended
  • For instance, the method to set the price variable is named: setPrice()
  • Usually, these methods take a parameter used to assign the new value
  • public void setPrice(double newPrice)
  • Set methods should verify the value is correct before setting it
  • For example:
  • public void setPrice(double newPrice) {
        if (newPrice > 0.0) {
            price = newPrice;
        } else {
            price = 0.0;
        }
    }
    

Get Methods

  • You often need retrieve values from private variables
  • You use public methods to retrieve the data
  • Methods of this type are called get methods (a.k.a. accessor methods)
  • The convention for naming these methods is to use the name of the variable with the word get prepended
  • For example:
  • public String getName() {
        return name;
    }
    

Other Instance Methods

  • You can code as many instance methods as needed for an object
  • However, all the instance methods should relate to the object type in a logical way
  • For example, the toString() method is a convenient way to display information about an object
  • public String toString() {
        return "The product is: " + name
            + " and the price is: " + price;
    }
    
  • If you print an object, Java will automatically call the toString() method
  • For example:
  • System.out.println(Product.toString());
    or just:
    System.out.println(Product);
  • As mentioned before, use verbs for method names
    • This is appropriate since they perform an action
  • Also start method names with a lower case letter
  • This is not required by the compiler, but is a convention that professional programmers follow

6.3.5: Summary

  • OOP addresses the problem of data protection through encapsulation and data hiding
  • Encapsulation and data hiding allow you to control the values assigned to the variables of an object
  • Classes define the instance variables and instance methods of a class
  • Instance variables store the data of an object
  • Instance methods are the operations that can occur on the object
  • Access modifiers control access to instance variables and methods
    • private: can only be accessed by member methods of this class
    • public: can be accessed by member methods of any class
  • Use private for all variables and public for most methods
  • Use "set" methods to control setting of new values to private variables
  • Use "get" methods to return values of private variables
  • Add other methods that are logically related to the object type

Check Yourself

  1. What is meant by the terms "encapsulation" and "data hiding"?
  2. What is the syntax for coding a class?
  3. How do you code instance variables?
  4. What are the differences between local variables and instance variables?
  5. How do you code instance methods?
  6. What two instance methods are coded if you need to access an instance variable?

Exercise 6.3

In this exercise we write our first class. A rectangle is a shape with a length and a width.

Specifications

  1. Save the following starter code files as Rectangle.java and RectangleTest.java.
  2. Write suitable declarations for instance variables named length and width.
  3. Code set and get methods for both of the variables following the recommended naming conventions.
    • Use the name of the variable with the word set prepended
    • Use the name of the variable with the word get prepended
  4. Write a toString() method that returns some information about the object as a string.
  5. Write a test class named RectangleTest with a main() method that instantiates one or more Rectangle objects, initializes each objects data and calls appropriate methods to display their length and width information.
  6. Submit your two classes along with your other exercises for this lesson.
public class Rectangle {
    // Put instance variables here

    // Put instance methods here

}
public class RectangleTest {
    public static void main(String[] args) {
        // place statements to instantiate objects here
    }
}

6.4: Constructors and Overloaded Methods

Objectives

At the end of the lesson the student will be able to:

  • Code constructors for a class and explain why they are used
  • Code overloaded constructors and methods
  • Describe how Java resolves overloaded method calls
  • Discuss when to overload methods

6.4.1: Defining Constructors

  • When you create an object from a class, you often want to initialize certain variables
  • A constructor is a special kind of method that is designed to perform such initialization
  • Syntax for declaring constructors:
  • [accessModifier] ClassName(parameter list) {
        // statements to initialize instance variables
        // other initializing statements as needed
    }
    
  • For now, use the public access modifier for all class constructors
    • Other objects call the constructor when creating new objects
  • Constructors must use the same name and capitalization as the class name
  • Constructors can have zero or more parameters, just like methods
  • However, note that constructors do not have a return type

Example: Constructor with two Parameters

  • We can code a constructor for our Product class
  • public Product(String newName, double newPrice) {
        setName(newName);
        setPrice(newPrice);
    }
    
  • Since our class has two instance variables, our constructor has two parameters
  • Now rather than creating an object like this:
  • Product milk = new Product();
    milk.setName("Milk");
    milk.setPrice(3.95);
    
  • We can create one like this:
  • Product milk = new Product("Milk", 3.95);
  • Note that when we add a constructor with parameters we must use that constructor to create objects
  • We can no longer create an object in steps using:
  • Product milk = new Product();
    milk.setName("Milk");
    milk.setPrice(3.95);
    

6.4.2: Overloading Constructors

  • What if you wanted to be able to create objects either with parameters or without parameters?
  • In Java you can create many constructors in each class
  • For instance, we can add a second constructor with no parameters
  • public Product() {
        name = "Unknown";
        price = 0.0;
    }
    
  • This is known as constructor (or method) overloading
  • You can have many constructors in a class, but each must have a different signature
  • The name of the constructor combined with the types in its parameter list form its signature)
  • For instance, we could add a third constructor to our Product class:
  • public Product(String newName) {
        setName(newName);
        price = 0.0;
    }
    

Default Constructors

  • If the programmer does not define a constructor, then the compiler supplies an empty one to the compiled code like the following:
  • public Product() {}
  • However, if the programmer defines any constructor, the compiler does not add this empty constructor

6.4.3: Overloading Methods

  • Just like you can overload constructors, you can overload methods
  • This means you can have several methods with the same name in a class
  • Just like constructors, you use the same method name but a different signature
    • Number of parameters
    • Parameter types
    • Order of parameters
  • Note that the return type is not part of the signature
    • You cannot use return types to distinguish between two methods with the same name and parameter list

For Example

  • Recall the setPrice() method of Product:
  • public void setPrice(double newPrice) {
        if (newPrice > 0.0) {
            price = newPrice;
        } else {
            price = 0.0;
        }
    }
    
  • Let us add another method that accepts the price in dollars and cents
  • public void setPrice(int dollars, int cents) {
        if (dollars > 0 && cents > 0) {
            price = (double) dollars + (cents / 100.0);
        } else {
            price = 0.0;
        }
    }
    
  • Note that both methods have the same name but different parameter lists

6.4.4: Overloading Resolution

  • So how does the compiler determine which method to call?
  • First it looks for an exact signature
    • Because no argument conversion required
  • If there is not an exact match, it looks for a "compatible" signature
    • Where automatic type conversion is possible:
  • Recall that Java automatically converts types as follows:
  • byte => short => int => long => float => double
                    /
             char =/
    

For Example

  • Given following methods:
    1. void foo(int n, double m) {}
    2. void foo(double n, int m) {}
    3. void foo(int n, int m) {}
  • Making these calls:
  • foo(98, 99); => Calls 3
  • foo(5.3, 4); => Calls 2
  • foo(5, 4.2); => Calls 1
  • foo(4.3, 5.2); => Compiler error

6.4.5: Overloading for Default Arguments

  • You can use overloading to omit some arguments
  • For example:
  • void showVolume(int length, int width, int height) {
        // Do something
    }
    
  • Want to provide default values for the last 2 arguments
  • Create 2 additional method calls
  • Each method calls the full method with default values
  • void showVolume(int length, int width) {
        showVolume(length, width, 1);
    }
    
    void showVolume(int length) {
        showVolume(length, 1, 1);
    }
    
  • Possible calls:
  • showVolume(1, 2, 3); // All arguments supplied
    showVolume(1, 2);    // height defaulted to 1
    showVolume(1);       // width & height defaulted to 1
    

6.4.6: Summary

  • Constructors are special methods designed to initialize the variables of an object
  • Constructors must use the same name and capitalization as the class name
  • However, constructors do not have a return type
  • public Product(String newName, double newPrice) {
        setName(newName);
        setPrice(newPrice);
    }
    
  • You can code zero or more constructors for a class
    • However, the parameter list must be different for each one
  • Constructors are called whenever an object is created from a class
  • If you do not code any constructor then the compiler supplies an empty one in the compiled code like the following:
  • public Product() {}
  • Just like constructors, a programmer can declare many methods using the same name
  • Useful when you want to have the same method operate on different data types
  • Another use of overloading is to code default arguments
  • Which allows calling methods with some arguments supplied by default values

Check Yourself

  1. How do you code a constructor for a class?
  2. When does a compiler automatically include a constructor?
  3. How many constructors can you define for each class definition?
  4. If two methods have the same name in a class, what must be different in each definition?
  5. How does Java resolve overloaded methods?
  6. When should you overload methods?

Exercise 6.4

In this exercise, we add two constructors to the Rectangle class of the previous exercise

Specifications

  1. Save the Rectangle and RectangleTest classes from the previous exercise as Rectangle2.java and RectangleTest2.java.
  2. Remember to change the names of both classes and to make sure they compile after changing their names.

  3. Code a constructor for the Rectangle2 class with no parameters that sets default values to the instance variables length and width.
  4. Code a constructor for the Rectangle2 class that takes two parameters newLength and newWidth. Assign newLength and newWidth to the correct instance variables.
  5. Update the RectangleTest2 class to create two objects, one using one constructor and another using the other constructor. After creating the objects, call the appropriate methods to display their length and width information.
  6. Submit your two new classes as the solution for this exercise.

Wrap Up

Home | WebCT | Announcements | Schedule | Expectations | Course info
Help | FAQ's | HowTo's | Links

Last Updated: November 06 2005 @16:45:09