Transcript

1

Java ProgrammingJava Programming

Using Methods, Classes, and Using Methods, Classes, and ObjectsObjects

22

Topics:Topics: Methods Methods

• with no arguments, with no arguments, • a single argument, a single argument, • multiple argumentsmultiple arguments• with return valueswith return values

Class conceptsClass concepts• Create a classCreate a class• Use instance methodsUse instance methods• Declare objectsDeclare objects• Organize classesOrganize classes• Use constructorsUse constructors

33

MethodMethod

A A method method is a series of statements is a series of statements that carry out a taskthat carry out a task

Any class can contain an unlimited Any class can contain an unlimited number of number of methodsmethods

44

MethodsMethods

Methods must include:Methods must include: A declarationA declaration An opening curly braceAn opening curly brace A bodyA body A closing braceA closing brace

55

MethodsMethods

Method declarations must contain:Method declarations must contain: Optional access modifiersOptional access modifiers The return type for the methodThe return type for the method The method nameThe method name An opening parenthesisAn opening parenthesis An optional list of method argumentsAn optional list of method arguments A closing parenthesisA closing parenthesis

66

Access ModifiersAccess Modifiers

Access modifiers for a method can be:Access modifiers for a method can be: public- most often methods are given public- most often methods are given

public accesspublic access privateprivate protectedprotected staticstatic

77

Access ModifiersAccess Modifiers

public- Endowing a method with public public- Endowing a method with public access means any class can use itaccess means any class can use it

static-static- Any method that can be used from Any method that can be used from anywhere within the class requires the anywhere within the class requires the keyword modifier keyword modifier staticstatic

88

Creating Methods that Require a Creating Methods that Require a Single ArgumentSingle Argument

Arguments- Are communications to a Arguments- Are communications to a methodmethod

Implementation hiding- Allows that the Implementation hiding- Allows that the invoking program must know the name of invoking program must know the name of the method and what type of information the method and what type of information to send it, but the program does not need to send it, but the program does not need to know how the method worksto know how the method works

99

Creating Methods that Require a Creating Methods that Require a Single ArgumentSingle Argument

The method declaration must include:The method declaration must include: The type of the argumentThe type of the argument A local name for the argumentA local name for the argument

• For example: For example:

public void predictRaise(double public void predictRaise(double moneyAmount)moneyAmount)

1010

Calling a MethodCalling a Method

Can use either argument:Can use either argument:• ConstantConstant• VariableVariable

predictRaise(472.55)predictRaise(472.55) predictRaise(mySalary)predictRaise(mySalary)

1111

Creating Methods that Require Creating Methods that Require Multiple ArgumentsMultiple Arguments

Methods can require more than one Methods can require more than one argumentargument

Pass multiple arguments by:Pass multiple arguments by:• Listing the arguments in the call to the Listing the arguments in the call to the

methodmethod• Separating them with commasSeparating them with commas

The declaration for a method that The declaration for a method that receives two or more arguments receives two or more arguments must list the type for each argument must list the type for each argument separatelyseparately

1212

A Method’s Return TypeA Method’s Return Type

The return type is known as the The return type is known as the method’s typemethod’s type

For example:For example:

public static void public static void nameAndAddress()nameAndAddress()

• This method is public and returns no value This method is public and returns no value

public static String public static String nameAndAddress()nameAndAddress()

• This method returns a string (with name and This method returns a string (with name and address)address)

1313

Return StatementReturn Statement

The return statement is the last The return statement is the last statement in a methodstatement in a method

Usually you use the returned value, Usually you use the returned value, but this is not requiredbut this is not required

1414

Overloading a MethodOverloading a Method

Overloading:Overloading: Involves using one term to indicate Involves using one term to indicate

diverse meaningsdiverse meanings Writing multiple methods with the Writing multiple methods with the

same name, but with different same name, but with different argumentsarguments

Overloading a Java method means you Overloading a Java method means you write multiple methods with a shared write multiple methods with a shared namename

1515

Overloaded methodsOverloaded methods Methods can be overloaded to support different Methods can be overloaded to support different

types of datatypes of data• Overloaded methods have the same name Overloaded methods have the same name and return and return

typetype (the latter is often forgotten)(the latter is often forgotten)• But the number and type of arguments can be changed But the number and type of arguments can be changed

to support different cases/scenariosto support different cases/scenarios• For exampleFor example

float calculateRaise(float Salary, float Raise_Amount );float calculateRaise(float Salary, float Raise_Amount );• 22ndnd argument represents raise in $ (float) argument represents raise in $ (float)

float calculateRaise(float Salary, int Percent_Amount);float calculateRaise(float Salary, int Percent_Amount);• 22ndnd argument represents raise in percent (integer) argument represents raise in percent (integer)

float calculateRaise(float Salary);float calculateRaise(float Salary);• No 2No 2ndnd argument, standard (constant raise) argument, standard (constant raise)

1616

Learning about Ambiguity Learning about Ambiguity

When you overload a method you run When you overload a method you run the risk of ambiguitythe risk of ambiguity• An ambiguous situation is one in which An ambiguous situation is one in which

the compiler cannot determine which the compiler cannot determine which method to usemethod to use

• Examples?Examples?

1717

Overloading ExampleOverloading Example

static float calculateRaise(float empSalary, float payRaise)static float calculateRaise(float empSalary, float payRaise){{

return empSalary + payRaise;return empSalary + payRaise;}}

static float calculateRaise(float empSalary, int payRaise)static float calculateRaise(float empSalary, int payRaise){{

return empSalary * (1 + (float)payRaise/100);return empSalary * (1 + (float)payRaise/100);}}

public static void main(String[] arg)public static void main(String[] arg){{ // why need “f” after constant// why need “f” after constant System.out.println("1: " + calculateRaise(100000.00f, 3000.00f)); System.out.println("1: " + calculateRaise(100000.00f, 3000.00f)); System.out.println("1: " + calculateRaise(100000.00f, 10)); System.out.println("1: " + calculateRaise(100000.00f, 10)); System.out.println("1: " + calculateRaise(100000, 10.0)); //doesn’t workSystem.out.println("1: " + calculateRaise(100000, 10.0)); //doesn’t work}}

1818

Class ConceptsClass Concepts

In object-oriented programming:In object-oriented programming: Everything is an objectEverything is an object An object is an instantiation of a class, or a An object is an instantiation of a class, or a

tangible example of a classtangible example of a class Every object is a member of a classEvery object is a member of a class

• Your desk is an object and is a member of the Your desk is an object and is a member of the Desk classDesk class

• These statements represent is-a relationshipsThese statements represent is-a relationships

1919

Class ConceptsClass Concepts

• The concept of a class is useful because:The concept of a class is useful because:• Objects inherit attributes from classesObjects inherit attributes from classes• All objects have predictable attributes because they are All objects have predictable attributes because they are

members of certain classes members of certain classes

• You must:You must:• Create the classes of objects from which objects will be Create the classes of objects from which objects will be

instantiated instantiated • Write other classes to use the objectsWrite other classes to use the objects

• Class Client or Class User-A program or class that Class Client or Class User-A program or class that instantiates objects of another prewritten classinstantiates objects of another prewritten class

2020

Creating a ClassCreating a Class

You must:You must: Assign a name to the classAssign a name to the class Determine what data and methods will be part of the classDetermine what data and methods will be part of the class

To begin, create a class header with three parts:To begin, create a class header with three parts: An optional access modifierAn optional access modifier The keyword classThe keyword class Any legal identifier you choose for the name of the classAny legal identifier you choose for the name of the class

The define the class contentsThe define the class contents Then add a open and close braceThen add a open and close brace Add the attributes (fields) and actions (methods) to the classAdd the attributes (fields) and actions (methods) to the class

2121

Access modifiers for ClassesAccess modifiers for Classes

Access modifiers include:Access modifiers include: public public

• This is the most used modifierThis is the most used modifier• Most liberal form of accessMost liberal form of access• Can be extended or used as the basis for other Can be extended or used as the basis for other

classesclasses final- used only under special final- used only under special

circumstancescircumstances abstract- used only under special abstract- used only under special

circumstancescircumstances

2222

Access modifiers for Fields and MethodsAccess modifiers for Fields and Methods

Private (default for fields) Private (default for fields) Public (default for methods)Public (default for methods) Static Static FinalFinal

2323

Field ModifiersField Modifiers

Private Private • No other classes can access a field’s No other classes can access a field’s

valuesvalues• Only methods of the same class are Only methods of the same class are

allowed to set, get, or otherwise use allowed to set, get, or otherwise use private variablesprivate variables

• Highest level of securityHighest level of security• Also called information hidingAlso called information hiding

Provides a means to control outside access to Provides a means to control outside access to your data your data

2424

Using Instance MethodsUsing Instance Methods

Methods used with object Methods used with object instantiations are called instance instantiations are called instance methodsmethods• You can call class methods without You can call class methods without

creating an instance of the class.creating an instance of the class.• Instance methods require an Instance methods require an

instantiated object.instantiated object.

2525

Declaring ObjectsDeclaring Objects

To declare an object:To declare an object: Supply a type and an identifierSupply a type and an identifier Allocate computer memory for the objectAllocate computer memory for the object

• Use the new operatorUse the new operator

2626

Organizing ClassesOrganizing Classes

Most programmers place data fields Most programmers place data fields in some logical order at the in some logical order at the beginning of a classbeginning of a class• For example, use a unique identifier for For example, use a unique identifier for

each employeeeach employee empNumempNum

• Last names and first names are Last names and first names are organized togetherorganized together

2727

Using Constructor MethodsUsing Constructor Methods

Constructor methods- Methods that Constructor methods- Methods that establish an objectestablish an objectEmployee chauffer = new Employee();Employee chauffer = new Employee();

Calls a method named Employee() that is Calls a method named Employee() that is provided by the Java compilerprovided by the Java compiler

Methods are commonly overloaded to Methods are commonly overloaded to provide various ways to initialize an objectprovide various ways to initialize an objectEmployee chauffer = new Employee(“Mike Employee chauffer = new Employee(“Mike

Elm”);Elm”);Employee chauffer = new Employee(“Mike Elm”, Employee chauffer = new Employee(“Mike Elm”,

2320);2320);

2828

ADVANCED TOPICSADVANCED TOPICS

2929

Advanced Topics:Advanced Topics: Understand blocks and scopeUnderstand blocks and scope Learn about ambiguityLearn about ambiguity Send arguments to constructorsSend arguments to constructors Overload constructorsOverload constructors Learn about the Learn about the thisthis reference reference Work with constantsWork with constants Use automatically imported, prewritten constants Use automatically imported, prewritten constants

and methodsand methods Use prewritten imported methodsUse prewritten imported methods

3030

Understanding BlocksUnderstanding Blocks

Blocks-Within any class or method, the Blocks-Within any class or method, the code between a pair of curly bracescode between a pair of curly braces• Outside block- The first block, begins Outside block- The first block, begins

immediately after the method declaration immediately after the method declaration and ends at the end of the method and ends at the end of the method

• Inside block- The second block, contained Inside block- The second block, contained within the second pair of curly braceswithin the second pair of curly braces

• The inside block is nested within the The inside block is nested within the outside block outside block

3131

Understanding ScopeUnderstanding Scope

The portion of a program within The portion of a program within which you can reference a variablewhich you can reference a variable

A variable comes into existence, or A variable comes into existence, or comes into scope, when you declare comes into scope, when you declare itit

A variable ceases to exist, or goes A variable ceases to exist, or goes out of scope, at the end of the block out of scope, at the end of the block in which it is declaredin which it is declared

3232

public class Testpublic class Test {{ public static void main(String[] args) throws Exception public static void main(String[] args) throws Exception {{ while (true)while (true) {{ int Count = 10;int Count = 10;

… ….. Count++; // this is okCount++; // this is ok

}}

for(int i = 0; i < MAX_NUM; i++)for(int i = 0; i < MAX_NUM; i++) {{

Count++; // this will generate an error, why?Count++; // this will generate an error, why? }}

} // end of main} // end of main }//end of class Test}//end of class Test

3333

Overriding a Method or VariableOverriding a Method or Variable

If you declare a variable within a class, If you declare a variable within a class, and use the same variable name within a and use the same variable name within a method of the class, then the variable method of the class, then the variable used inside the method takes precedence, used inside the method takes precedence, or overrides, the first variableor overrides, the first variable

In Java you can override variables and In Java you can override variables and methodsmethods• Variable overriding is confusing and should be Variable overriding is confusing and should be

avoidedavoided• Method overriding is useful and necessaryMethod overriding is useful and necessary

3434

ConstructorsConstructors

Java automatically provides a constructor Java automatically provides a constructor method when you create a classmethod when you create a class

Programmers can write their own Programmers can write their own constructor methodsconstructor methods

Programmers can also write constructors Programmers can also write constructors that receive argumentsthat receive arguments• Such arguments are often used for initialization Such arguments are often used for initialization

purposes when values of objects might varypurposes when values of objects might vary

3535

Overloading ConstructorsOverloading Constructors

If you create a class from which you If you create a class from which you instantiate objects, Java automatically instantiate objects, Java automatically provides a constructorprovides a constructor

But, if you create your own constructor, the But, if you create your own constructor, the automatically created constructor no longer automatically created constructor no longer existsexists

As with other methods, you can overload As with other methods, you can overload constructorsconstructors• Overloading constructors provides a way to Overloading constructors provides a way to

create objects with or without initial arguments, create objects with or without initial arguments, as neededas needed

3636

Using the Using the thisthis Reference Reference

Classes can become large very quicklyClasses can become large very quickly• Each class can have many data fields and methodsEach class can have many data fields and methods

If you instantiate many objects of a class, the If you instantiate many objects of a class, the computer memory requirements can become computer memory requirements can become substantialsubstantial• It is not necessary to store a separate copy of each It is not necessary to store a separate copy of each

variable and method for each instantiation of a classvariable and method for each instantiation of a class

The compiler accesses the correct object’s The compiler accesses the correct object’s data fields because you implicitly pass a data fields because you implicitly pass a thisthis reference to class methodsreference to class methods

Static methods, or class methods, do not have Static methods, or class methods, do not have a a thisthis reference because they have no object reference because they have no object associated with themassociated with them

3737

3838

Class VariablesClass Variables

Class variables- Variables that are Class variables- Variables that are shared by every instantiation of a shared by every instantiation of a classclass

Class variables (and methods) are Class variables (and methods) are also refered to as “static” variables also refered to as “static” variables (or methods) because of the access (or methods) because of the access modifier used to define themmodifier used to define them

3939

Working with ConstantsWorking with Constants

Constant variable:Constant variable: A variable or data field that should A variable or data field that should

not be changed during the execution not be changed during the execution of a programof a program• To prevent alteration, use the keyword To prevent alteration, use the keyword

finalfinal Constant fields are written in all Constant fields are written in all

uppercase lettersuppercase letters• For example:For example:

COMPANY_IDCOMPANY_ID

4040

Using Automatically Imported, Using Automatically Imported, Prewritten Constants and MethodsPrewritten Constants and Methods

The creators of Java created nearly The creators of Java created nearly 500 classes 500 classes • For example:For example:

System, Character, Boolean, Byte, Short, System, Character, Boolean, Byte, Short, Integer, Long, Float, and Double are classesInteger, Long, Float, and Double are classes

These classes are stored in a package, or a These classes are stored in a package, or a library of classes, which is a folder that library of classes, which is a folder that provides a convenient grouping for classesprovides a convenient grouping for classes

4141

java.lang – The package that is java.lang – The package that is implicitly imported into every Java implicitly imported into every Java program and contains fundamental program and contains fundamental classes, or basic classesclasses, or basic classes

Fundamental classes include:Fundamental classes include:• System, Character, Boolean, Byte, Short, System, Character, Boolean, Byte, Short,

Integer, Long, Float, and Double Integer, Long, Float, and Double Optional classes – Must be explicitly Optional classes – Must be explicitly

namednamed

Using Automatically Imported, Prewritten Constants and Methods

4242

Using Prewritten Imported MethodsUsing Prewritten Imported Methods

To use any of the prewritten classesTo use any of the prewritten classes (other than java.lang):(other than java.lang):• Use the entire path with the class Use the entire path with the class

namenameOROR• Import the classImport the classOROR• Import the package which contains the Import the package which contains the

class you are usingclass you are using

4343

Using Prewritten Imported MethodsUsing Prewritten Imported Methods

To import an entire package of To import an entire package of classes use the wildcard symbolclasses use the wildcard symbol• **

For example:For example:• import java.util.*;import java.util.*;

• Represents all the classes in a packageRepresents all the classes in a package

4444

Access SpecifiersAccess Specifiers

http://www.uni-bonn.de/~manfear/javamodifiers.php

4545

Key Concepts Learned TodayKey Concepts Learned Today ObjectsObjects ClassesClasses Constructors Constructors Overloaded constructorsOverloaded constructors Method declarationsMethod declarations Scope specifiersScope specifiers

4646

Next Week:Next Week:

Key topicsKey topics• Advanced OOP conceptsAdvanced OOP concepts• InheritanceInheritance• AggregationAggregation• EncapsulationEncapsulation

Read Chapter 9Read Chapter 9 Read Articles in eResource (Week 4 and 5)Read Articles in eResource (Week 4 and 5)

• ArraysArrays• ObjectsObjects

Review WS4 Programming assignmentReview WS4 Programming assignment Team project approvalTeam project approval


Top Related