You are on page 1of 45

Object Oriented Programming

Member Methods, Method Overloading

1
Reference: Liang, Y., 2015. Intro To Java Programming. 10th ed. Pearson Education Limited .
Unit Topics
1. Member methods of a class
2. Argument Types
3. Passing Object to method, returning Object from method, Array of
objects
4. Method Overloading
5. Type Conversion in Method Overloading
6. Constructor Overloading and this Keyword

2
Unit 4.1

Declaring Methods
• In order for an object A to request some service of an object B, A needs to
know the specific language with which to communicate with B. That is,
– Object A needs to be clear as to exactly which of B’s methods/services
A wants B to perform.
– Depending on the service request, object A may need to give B some
additional information so that B knows exactly how to proceed.
– Object B in turn needs to know whether object A expects B to report
back the outcome of what it has been asked to do.

3
Unit 4.1

Methods
• A method definition consists of its method name, parameters, return
value type, and body.
• Methods can be used to define reusable code and organize and simplify
code. A method is a collection of statements grouped together to perform
an operation..
• Syntax

• If a method returns a value, it is called a value returning method,


otherwise it is called a void method.
• Some programming languages refer to methods as procedures and
functions.

4
Unit 4.1

Method Headers
• A method header is a formal specification (from a programming
standpoint) of how that method is to be invoked. A method header, at
minimum, consists of
• A method’s return type—that is, the type of information that is going
to be returned by object B to object A, if any, when B’s method finishes
executing.
• A method’s name.
• An optional list of comma-separated formal parameters (specifying
their types and names) to be passed to the method, enclosed in
parentheses.

5
Unit 4.1

6
Unit 4.1

Method Naming Conventions


• Java method names are crafted using the camel casing style;
o The first letter of the method name is in lowercase.
o The first letter of each subsequent concatenated word in the method
name is in uppercase, and the remaining characters are in lowercase.
o We don’t use any “punctuation” characters—dashes, underscores, etc.
—to separate these words.

Method Properties
• Can be declared in any order
• A return statement is a jump statement that is used to exit a method.
• Method implements business rule.

7
Unit 4.1

Passing Arguments to Methods


• The purpose of passing arguments into a method is two fold:
• To provide it with the (optional) “fuel” necessary to do its job
• To otherwise guide Its behavior in some fashion

boolean registerForCourse(String courseID, int secNo)


int getAge(int ageType)

– Parameter, e.g String getMyFood(String timing)


– Argument, e.g. int a = Math.pow(2,4)

8
Unit 4.1

An Analogy
• let’s say that a person is capable of
• Taking out the trash
• Mowing the lawn
• Washing the car

• Expressing this notion in Java code, we’d perhaps declare three methods
for the Person class, one for each chore (service):
• void takeOutTheTrash()
• boolean mowTheLawn()
• void washTheCar(Car c)

9
Unit 4.1

Calling a method
• Calling a method executes the code in the method.
• To execute the method, It has to be called or invoke.
• There are two ways to call a method, depending on whether the method
returns a value or not.
1. If method returns a value;.

2. If a method returns void, a call to the method must be a statement.

• When a program calls a method, program control is transferred to the


called method. A called method returns control to the caller when its
return statement is executed or when its method ending closing brace is
reached.

10
Unit 4.1

Capturing the Value Returned by a Method


boolean registerForCourse(String courseId, int
sectionNumber)

x.registerForCourse("MATH 101", 10);

boolean successfullyRegistered = x.registerForCourse("MATH


101", 10);

11
Unit 4.1

Parameters
• The power of a method is its ability to work with parameters.
• When calling a method, you need to provide arguments, which must be
given in the same order as their respective parameters in the method
signature. This is known as parameter order association.
• When a method is invoked with an argument, the value of the argument is
passed to the parameter.
• If the argument is a variable rather than a literal value, the value of the
variable is passed to the parameter.

12
Unit 4.1

Method Signatures
void switchMajor(String newDepartment, Professor newAdvisor)

• We refer to a method’s signature as those aspects of a method header


that are “discoverable” by inspecting the code used to invoke the method,
namely,
• The method’s name
• The order, types, and number of parameters declared by the
method
• but excluding
• The parameter names
• The method’s return type

13
Unit 4.1

Examples
• Method header: int getAge(int ageType)
• Method signature: getAge(int)
• Argument signature: (int)
• Method header:
void chooseMajor(String newDepartment, Professor newAdvisor)
• Method signature: chooseMajor(String, Professor)
• Argument signature: (String, Professor)

14
Unit 4.2

Argument Passing
• In general, there are two ways that a computer language can pass an
argument to a subroutine.
• call-by-value
This approach copies the value of an argument into the formal parameter
of the method. Therefore, changes made to the parameter of the method
have no effect on the argument.
• call-by-reference
In this approach, a reference to an argument (not the value of the
argument) is passed to the parameter. Inside the method, this reference is
used to access the actual argument specified in the call. This means that
changes made to the parameter will affect the argument used to call the
method.

15
Unit 4.2

call-by-value

Output

16
Unit 4.2

call-by-reference

Output

17
Unit 4.3

Objects as Parameters
• Just like using simple types as parameters, it is both correct and common
to pass objects to methods.

18
Unit 4.3

Objects as Parameters
• One of the most common uses of object parameters involves
constructors. Frequently, a construct is required to create a new object
that it is initially the same as some existing object.

19
Unit 4.3

Objects as Parameters

Output:
Volume of the mybox1 is 3000
Volume of the clone is 3000

20
Unit 4.3

Returning Objects
A method can return any type of data,
including class types that is created.

Output

21
Unit 4.3

Returning Objects

Output

Is an object going out-of-scope?

22
Unit 4.3

Returning Objects

Output

No

The object will continue to exist as


long as there is a reference to it
somewhere in the program. When
there are no references to it, the
object will be reclaimed the next
time garbage collection takes place.

23
Unit 4.3

Array of Objects
Circle[] circleArray = new Circle[10];

• An array of objects is actually an array of reference variables.


• So invoking circleArray[1].getArea() involves two levels of referencing
as shown in the next figure.
– circleArray references to the entire array.
– circleArray[1] references to a Circle object.

24
Unit 4.3

Array of Objects

Circle[] circleArray = new Circle[10];

circleArray reference circleArray[0] Circle object 0


circleArray[1]

… Circle object 1

circleArray[9] Circle object 9

25
Unit 4.3

Review Questions
1. What are the difference between method signature and method
header?
2. What is Object cloning?
3. What do you mean by returning an object from method?
4. How do define the array of object? Why array of object is useful?

26
Unit 4.4

Method Overloading
• Overloading is a language mechanism that allows two or more
different methods belonging to the same class to have the same
name as long as they have different argument signatures

• The methods are said to be overloaded, and the process is referred to as


method overloading.
• Method overloading is one of the ways that implements polymorphism.

27
Unit 4.4

Method Overloading
void print (String fileName)
{ ... // version #1
void print (int detailLevel)
{ ... // version #2
void print (int detailLevel, String fileName)
{ ... // version #3
int print (String reportTitle, int maxPages)
{ ... // version #4
boolean print ()
{ ... // version #5

28
Unit 4.4

Method Overloading
• When an overloaded method is invoked, Java uses the type and/or
number of arguments as its guide to determine which version of the
overloaded method to actually call.
• Overloaded methods must differ in the type and/or number of their
parameters.
• The return type alone is insufficient to distinguish two versions of a
method.
• Method overloading increases the readability of the program

29
Unit 4.4

Implementing Method Overloading

30
Unit 4.4

Calling overloaded Methods

31
Unit 4.5

Type conversion in Method Overloading


• The method matching need not always be exact.
• In some cases, Java’s automatic type conversions can play a role in
overload resolution.

32
Unit 4.5

Type conversion in Method Overloading


• Java will employ its automatic type conversions only if no exact match is
found.

33
Unit 4.6

Constructor Overloading
• In addition to this, constructors can also be overloaded.
• Constructor overloading is a technique in Java in which a class can have
any number of constructors that differ in parameter lists.
• The compiler differentiates these constructors by taking into account the
number of parameters in the list and their type.
• Constructor returns current class instance yet it does not have a return
type.

Object Oriented Programming 34


Unit 4.6

Which method will be called?

35
Unit 4.6

Error!

36
Unit 4.6

The this Keyword


• this is always a reference to the object on which the method was invoked.
• this lets program refer directly to the current object
• It can be used anywhere a reference to an object of the current class’ type
is permitted.
• When a local variable has the same name as an instance variable, the local
variable hides the instance variable. It can be used to resolve any name
collisions.

37
Unit 4.6

Using this to access current object

38
Unit 4.6

Using this to avoid name collision

39
Unit 4.6

Using this to invoke constructor

• this() can be used to invoke current class constructor


• It can also be used inside a constructor to invoke another constructor of the
same class
• Call to this() must be the first statement in constructor.

40
Unit 4.6

other Usages of this


1. this keyword can be used to refer current class instance variable.
2. this keyword can be used to invoke current class method (implicitly)
If this is not used, compiler automatically adds this keyword while
invoking the method.
3. this can be passed as an argument in the method call for method in same
class.
4. this can be passed as argument in the constructor call.
5. this keyword can also be used to return the current class instance.

return_type method_name(){
return this;
}

41
Unit 4.6

What is wrong in the following code?

42
Unit 4.6

What is wrong in the following code?

43
Unit 4.6

44
Unit 4.6

Review Questions
1. Why this keyword is used?
2. Make an analogy to understand the concept of polymorphism.
3. How do you define method overloading is useful for the program
development?

45

You might also like