+ All Categories
Home > Documents > Defining Classes and Methods

Defining Classes and Methods

Date post: 02-Jan-2016
Category:
Upload: beck-davenport
View: 40 times
Download: 0 times
Share this document with a friend
Description:
Defining Classes and Methods. Chapter 4.1. Key Features of Objects. An object has identity (it acts as a single whole). An object has state (it has various properties, which might change). An object has behavior (it can do things and can have things done to it). - PowerPoint PPT Presentation
Popular Tags:
40
Defining Classes and Methods Chapter 4.1
Transcript
Page 1: Defining Classes and Methods

Defining Classes and Methods

Chapter 4.1

Page 2: Defining Classes and Methods

Key Features of Objects

• An object has identity (it acts as a single whole).

• An object has state (it has various properties, which might change).

• An object has behavior (it can do things and can have things done to it).

• An object belongs to a class.(cf. Object-oriented Analysis and Design, by Grady Booch, Addison-Wesley, 1994.)

Page 3: Defining Classes and Methods

Objects of a Class

Page 4: Defining Classes and Methods

Basic Terminology• Objects can represent almost anything.• A class defines a family of objects.

– It specifies the kinds of data an object of the class can have.

– It provides methods specifying the actions an object of the class can take.

• An object is an instance of the class. • We will call the data items associated with an

object the instance variables of that object (i.e. that instance of the class).

Page 5: Defining Classes and Methods

Object Oriented Programming: three stages

• Creating the program:– define classes that describe objects that the program will

use when it is running.– including one class that contains the static main() method

which is used to start the program running

• Compiling the program– translation to bytecode

• Running the program– The java interpreter looks for a static main() method

and starts running.– The program does its work by creating objects and invoking

their methods. The order of creation and invocation depends upon the problem at hand.

Page 6: Defining Classes and Methods

Class Files and Separate Compilation

• Each Java class definition should be in a file by itself.

• A Java class can be compiled before it is used in a program

• If all the classes used in a program are in the same directory (folder) as the program file, you do not need to import them.

Page 7: Defining Classes and Methods

Syntax of Class Definitions

class ClassName

{

Descriptions of the instance variables and methods each object will have and the constructors that initialize a new object.

}

Page 8: Defining Classes and Methods

Class Definition

• Often the class definition is segmented for clarity as follows

class ClassName

{

// Description of the variables.

// Description of the constructors.

// Description of the methods

}

Page 9: Defining Classes and Methods

Checkpoint

• A program is a class that has a method named main

• Does every class require a main( ) method?

Page 10: Defining Classes and Methods

Object Oriented Helloclass HelloObject{ // method definition

void speak() { System.out.println("Hello from an object!"); }

}class HelloTester{ // method definition public static void main ( String[] args ) { HelloObject anObject = new HelloObject(); anObject.speak(); }}

Page 11: Defining Classes and Methods

What Happens

class HelloObject{ // method definition

void speak()

{ System.out.println("Hello from an object!"); }

}class HelloTester{ // method definition public static void main (

String[] args ) { HelloObject anObject =

new HelloObject(); anObject.speak(); }}

1 main starts running2 New HelloObject is

created3 it is assigned to

anObject4 speak method of anObject

is invoked.5 A message is printed on

the screen.6. The program finishes

Page 12: Defining Classes and Methods

speak( ) method requiresanObject to contain it

Page 13: Defining Classes and Methods

Methods and Objects

• In general, methods require an object to be present in order to be invoked.

• However, this is not always the case.

• Static methods can be invoked by themselves.

• main is an example of a static method

Page 14: Defining Classes and Methods

More Complex Example

• SpeciesFirstTry.javaThis a class which defined three methods.

• SpeciesFirstTryDemo.javaThis is another class which invokes the first one.

• Both definitions live in the same directory (folder) – so there is no need for the second to import the first.

Page 15: Defining Classes and Methods

Two Kinds of Method

• methods that return a single value (e.g. nextInt)

• methods that perform some action other than returning a single value (e.g println), called void methods

Page 16: Defining Classes and Methods

Aspects of Methods

Methods

Definition Invocation

Methods that return a value

Void MethodsMethods that

Return a valueVoid Methods

Page 17: Defining Classes and Methods

void Method Definitions

examplepublic void writeOuput()

{

System.out.println(“Name: “ + name);

System.out.println(“Age: “ + age);

}

• Such methods are called void methods.

Page 18: Defining Classes and Methods

Definition ofMethods That Return a Value

examplepublic int fiveFactorial();

{

int factorial = 5*4*3*2*1;

return factorial;

}

• As before, the method definition consists of the method heading and the method body.– The return type replaces void.

Page 19: Defining Classes and Methods

Method Definitions, cont.• The parentheses following the method name contain any

information the method needs.

public int fiveFactorial();• In this case there is no information since there is nothing

between parentheses• Sometimes, however, we do include such information in the

form of a parameter list e.g.

public int sum(int i, j);• The parameter list gives the order and types of arguments• This first part of the method definition is called the heading.• The remainder of the method is called the body, and is enclosed

in braces {}.

Page 20: Defining Classes and Methods

Defining Methods That Return a Value, cont.

• The body of the method contains declarations and statements.

• The body of the method definition must contain

return Expression;– This is called a return statement.– The Expression must produce a value of

the type specified in the heading.

Page 21: Defining Classes and Methods

Using return in a void Method

• A void method is not required to have a return statement.

• However, it can be user to terminate the method invocation before the end of the code, to deal with some problem,

• form

return;

Page 22: Defining Classes and Methods

Invocation of Methodsthat Return a Value

example

int next = keyboard.nextInt();– keyboard is the calling object.– keyboard.nextint() is the invocation.– You can use the invocation any place that

it is valid to use of value of the type returned by the method.

Page 23: Defining Classes and Methods

Invocation of Methods that Do Not Return a Value

example

System.out.println(“Enter data:”);– System.out is the calling object.– System.out.println() is the invocation.

• The method invocation is a Java statement that produces the action(s) specified in the method definition.

• It is as if the method invocation were replaced by the statements and declarations in the method definition.

Page 24: Defining Classes and Methods

Variables

• A class definition is associated with different kinds of variables.– variables that are declared in the class– variables that declared in the methods

defined within the class.

Page 25: Defining Classes and Methods

The Class Bank Account

public class BankAccount

{

public double amount;

public double rate;

public void showNewBalance( )

{

double newAmount = amount + (rate/100.0)*amount;

System.out.println("amount is $" + newAmount);

}

}

Page 26: Defining Classes and Methods

Variables

• When an instance of a class is created, a new instance of each variable declared in the class is created.

• These variables are instance variables.

• Instance variables declared to be public can be accessed from outside the class.

Page 27: Defining Classes and Methods

Accessing Instance Variables

• Outside the class definition, a public instance variable is accessed with– objectname . instancevariable name

aBankAccount.rate = 10;• Inside the definition of the same class only

the name of the instance variable is used.

amount + (rate/100.0)*amount

Page 28: Defining Classes and Methods

Use of this• Inside the definition of the same class

only the name of the instance variable is used.amount + (rate/100.0)*amount

• Equivalently this stands for the calling object - the object that invokes the method.this.amount + (this.rate/100.0) * this.amount

Page 29: Defining Classes and Methods

Local Variables

• Variables that belong to the methods are private to the method.

• They are called local variables

• They cannot be accessed from outside the method in which they are defined.

Page 30: Defining Classes and Methods

Identify the Local Variable

public class BankAccount

{

public double amount;

public double rate;

public void showNewBalance( )

{

double newAmount = amount + (rate/100.0)*amount;

System.out.println("amount is $" + newAmount);

}

}local variable

instance variables

Page 31: Defining Classes and Methods

What is the Output?

public class LocalVariablesDemoProgram{ public static void main(String[] args) { BankAccount myAccount = new BankAccount( ); myAccount.amount = 100.00; myAccount.rate = 5; double newAmount = 800.00; myAccount.showNewBalance( ); System.out.println("I wish my new amount were $" + newAmount); }}

Page 32: Defining Classes and Methods

Blocks

• The terms block and compound statement both refer to a set of Java statements enclosed in braces {}.

• A variable declared within a block is local to the block.– When the block ends, the variable

disappears.• If you intend to use the variable both inside

and outside the block, declare it outside the block.

Page 33: Defining Classes and Methods

Local Varables

{ int x = 1, y = 2;

{ int x = 3;

x = x + y;

System.out.println(x);

}

x = x + y;

System.out.println(x);

}

Page 34: Defining Classes and Methods

Constructors

• Every class is associated with one or more constructors.

• A constructor is a method which constructs an instance of a class.

• Below a constructor invocation is shown in redBankAccount ac = new BankAccount( )

Page 35: Defining Classes and Methods

Default Constructor

• If a constructor is not defined explicitly within the class definition, it receives a default definition.

• The default definition is a method without arguments whose name is the same as that of the class.

• The default constructor behaves as though it were defined as shown in red.

Page 36: Defining Classes and Methods

Default Constructor

class HelloObject { HelloObject() // default constructor { } void speak(){ System.out.println("Hello from an object!"); }

} • Because the default constructor exists we can write new HelloObject().

• Note that it has an empty argument list.

Page 37: Defining Classes and Methods

Improving HelloObject – Step 1

• The first step is to provide the speak method with a variable, in this case greeting, to hold the greeting string.

class HelloObject { String greeting; void speak() { System.out.println(greeting); } } • How does greeting receive a value?

Page 38: Defining Classes and Methods

Assigning to greeting

• What we want is to be able to write something like this: {hello = new HelloObj(“hello”),goodbye = newHelloObj(“goodbye”);hello.speak();goodbye.speak();

}• In other words, we want to convey information to the

object through parameters of the constructor.• The problem is that the default constructor for HelloObj

has no parameters.

Page 39: Defining Classes and Methods

• The instance variable has to be set by the constructor – which means that the constructor has to have one parameter.

• We therefore cannot use the default constructor, and have to write our own.

• Further details are given in Kjell Chapter 30

Page 40: Defining Classes and Methods

How Values are Transmitted

• The method invocation, e.g. HelloObject(″Goodbye″)evaluates the supplied argument (actual parameter)

• The value of the argument is assigned to the method's corresponding formal parameter.

• The method computes with the parameter set to that value.

• This is known as the call-by-value mechanism.


Recommended