class and method definitions. uml class diagram automobile - fuel: double - speed: double - license:...

30
Class and Method Definitions

Upload: angela-brown

Post on 19-Jan-2016

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Class and Method Definitions

Page 2: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

UML Class Diagram

Automobile - fuel: double

- speed: double

- license: String

+ increaseSpeed(double howHardPress): void

+ stop(double howHardPress): void

Page 3: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Class Files and Separate Compilation Each Java class definition should be in a file by

itself. The name of the file should be the same as the

name of the class, and the file name should end in .java.

You can compile a Java class before you have a program in which to use it.

The compiled byte-code for the class will be stored in a file of the same name but ending in .class.

Page 4: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Class Files and Separate Compilation (cont’d) Later you can compile a program file with a main part that uses classes that you have already compiled.

Every program with a main part has a class name at the start of the file; this is the name you need to use for the file that holds the program.

As long as all the classes you use in a program are in the same directory as the program file, you don’t need to worry about directories.

Page 5: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Example of a Class Definition

import java.util.*;Public class Species{

public String name;public int population;public double growthRate;

public void readInput(){

Scanner keyboard = new Scanner(System.in);System.out.println(“What is the species’ name?”;name = keyboard.nextLine();System.out.println(“What is the population of the species?”);population = keyboard.nextInt();while (population < 0){

System.out.println(“Population cannot be negative.”);System.out.println(“Reenter population:”);population = keyboard.nextInt();

}System.out.println(“Enter growth rate (percent increase per year:”);growthRate = keyboard.nextDouble();

}

Page 6: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Example of a Class Definition (cont’d)

public void writeOutput(){

System.out.println(“Name = “ + name);System.out.println(“Population = “ + population);System.out.println(“Growth rate = + growthRate + “%”);

}

public int populationIn10(){

double populationAmount = population;int count = 10;while ((count > 0) && (populationAmount > 0)){

populationamount = (populationAmount +

(growthRate/100)*populationAmount);count--;

}if (populationAmount > 0)

return (int)populationAmount;else

return 0;}

}

Page 7: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Instance Variables

The class name in the previous example is Species.

The class is designed to hold records of endangered species.

Each object in the class has three pieces of data: a name, a population size, and a growth rate.

Objects of this class have three methods: readInput, writeOutput, and populationIn10.

Page 8: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Instance Variables (cont’d)

The data items and methods are called members of the object.

The data items are sometimes called fields, but we will refer to them as instance variables.

In the previous example the instance variables were name, population, and growthRate.

The word public simply means that there are no restrictions on how these variables are used.

An object is a complex item with instance variables inside it.

Page 9: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Example of a Program that Uses the Class Speciespublic class SpeciesDemoProgram{

public static void main(String[] args){

Species speciesOfTheMonth = new Species();int futurePopulation;System.out.println(“Enter data on the Species of the

Month:”);speciesOfTheMonth.readInput();speciesOfTheMonth.writeOutput();futurePopulation = speciesOfTheMonth.populationIn10();System.out.println(“In ten years the population will be “

+ futurePopulation);speciesOfTheMonth.name = “Klingon ox”;speciesOfTheMonth.population = 10;speciesOfTheMonth.growthRate = 15;System.out.println(“The new Species of the Month:”);speciesOfTheMonth.writeOutput();System.out.println(“In ten years the population will be “

+ speciesOfTheMonth.populationIn10());}

}

Page 10: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Example of a Program that Uses the Class Species (cont’d)

You can refer to one of the instance variables of speciesOfThemonth by writing the object name followed by a dot and then followed by the instance variable’s name, e.g., speciesOfTheMonth.name

Each instance variable has a type, and the type of the previous example is String.

Page 11: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Example of a Program that Uses the Class Species (cont’d)

The new is used to create a new object of the class Species.

You can think of it as creating the instance variables of the object.

Page 12: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Using Methods

All methods perform some action or actions.

Some return a value, e.g., nextInt. Some do not, e.g., println. A method defined in a class is usually

invoked using an object of that class. This object is known as the calling object, e.g., keyboard.nextInt();

Page 13: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Using Methods (cont’d)

You invoke a method by writing the calling object followed by a dot, then the name of the method, and finally a set of parentheses that may or may not have information to pass to the method.

If the method invocation returns a value, then you can use the method invocation anyplace that you are allowed to write a value of the type returned by the method, e.g., futurePopulation = speciesOfTheMonth.populationIn10();

Page 14: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Using Methods (cont’d)

If the method invocation does not return a value, then you place a semicolon after the method invocation and that produces a Java statement, e.g.,

speciesOfTheMonth.readInput();

Page 15: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Void Method Definitions

Each method definition is given inside the definition of the class to which it belongs.

The definition of a method that does not return a value starts with the keywords public void.

The word void means that nothing is returned. The keyword public may be replaced with

other words that restrict the use of the method.

Page 16: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Void Method Definitions (cont’d)

The first part of the method definition is called the heading.

The statements that follow, enclosed in braces { } are referred to as the body.

When a void method is invoked it is as if the method invocation were replaced with the body of the method where the instance variable names are replaced with those specific to the calling object, e.g., name is replaced by speciesOfTheMonth.name

Page 17: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Void Method Definitions (cont’d)

A program definition is just a class definition that has a method named main.

When you run a program you are simply invoking the void method that is name main.

The extra words static and String [] args will be explained later.

Page 18: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Methods that Return a Value

Methods that return a value are defined the same way as those that don’t with the following exceptions: Instead of the word void the type of the value

returned by the method is given, e.g.,

public int populationIn10() The body of the method must contain one or more

return statements to return a value, e.g.,

return (int)populationAmount;

Page 19: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Naming Methods

Choose clear meaningful names. It’s usually a good idea to use verbs to name

methods that perform some action but do not return values, e.g. println.

Nouns are usually the best choice for methods that return a value, e.g., populationIn10.

By convention, methods begin with lowercase letters, and class names begin with uppercase

Page 20: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Use of return in void Methods

A return statement can also be used in methods that do not return values just to cause the method to terminate and return control to the method it was invoked from.

In this case you simply say return; with nothing following the return.

Page 21: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

The this Parameter

When giving a method definition, you can use the keyword this as a name for the calling object.

For example, in the definition the writeOutput() method of the Species class we wrote,

System.out.println(“name = “ + name);

We could have written,

System.out.println(“name = “ + this.name);

Page 22: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

The this Parameter (cont’d)

You can think of this as just a place holder for the calling object to be given when the method is invoked.

this is usually omitted although there are some situations where it is needed.

Page 23: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Local Variables

Methods usually declarations for variables used within them beyond those declared in the class.

These are local to the method in which they are declared and cannot be used outside the method.

Two methods may have variables of the same name but they are treated as separate variables.

Page 24: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Blocks

A block is any set of Java statements enclosed within braces ({}).

Sometimes blocks are referred to as compound statements.

If you declare a variable within a block, it is not valid outside the block.

In Java you cannot use the same name for different variables in different blocks even though it is valid only in the block where it is declared.

Page 25: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Parameters of a Primitive Type

The method populationIn10 for the class Species returns the projected population of a species 10 years in the future.

If we wanted to generalize this method to calculate the projected population for any number of years in the future we could pass number of years as a parameter to the method.

Page 26: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Revised Method for Projecting Population

public int projectedPopulation(int years){

double populationAmount = population;int count = years:while ((count > 0) && (populationAmount > 0)){

populationamount = (populationAmount +

(growthRate/100)*populationAmount);count--;

}if (populationAmount > 0)

return (int)populationAmount;else

return 0;}

Page 27: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Example of Using a Method with a Parameterpublic class SpeciesDemoProgram2{

public static void main(String[] args){

Species speciesOfTheMonth = new Species();int futurePopulation;System.out.println(“Enter data on the Species of the

Month:”);speciesOfTheMonth.readInput();speciesOfTheMonth.writeOutput();futurePopulation =

speciesOfTheMonth.projectedPopulation(10);System.out.println(“In ten years the population will be “

+ futurePopulation);speciesOfTheMonth.name = “Klingon ox”;speciesOfTheMonth.population = 10;speciesOfTheMonth.growthRate = 15;System.out.println(“The new Species of the Month:”);speciesOfTheMonth.writeOutput();System.out.println(“In ten years the population will be “

+ speciesOfTheMonth.projectedPopulation(10));}

}

Page 28: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Formal Parameters and Arguments

In the projectedPopulation(int years) method definition the word years is called a formal parameter or simply a parameter.

It is a stand-in for a value that will be plugged in when the method is invoked.

The item that is plugged in is called an argument ( or sometimes an actual parameter).

Page 29: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Formal Parameters and Arguments (cont’d) In the invocation:

futurePopulation = speciesOfTheMonth.projectedPopulation(10);

the value 10 is an argument. It is important to note that only the value of the

argument is used in this substitution process. If the argument is a variable only the value of the variable is plugged in, not the name of the variable. This is called call-by-value.

Page 30: Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void

Correspondence Between Formal Parameters and Arguments

Formal parameters are given in parentheses after the method name at the beginning of a method definition.

In a method invocation, arguments are given in parentheses after the method name.

There must be exactly the same number of arguments as formal parameters, and they must be given in the same order.