Learning Outcome F.1. Creating User-Defined Classes in Programs To Promote Software Reuse. - Methods
Learning Outcome F.1. Creating User-Defined Classes in Programs To Promote Software Reuse. - Methods
(PPB115D/PPG115D/PPBFD/PPGF15D)
Compiled
by
Miss V. Booi
And
Mr M. Liebenberg
All rights reserved. Apart from any fair dealing for the purpose of research
criticism or review as permitted under Copyright Act, no part of this
document may be reproduced or transmitted in any other form or by any
means, electronic or mechanical, including photocopy and recording, without
permission in writing from the publisher.
1
1. Methods:
A method is a block of code which only runs when it is called. You can pass data, known as
parameters, into a method. Methods are used to perform certain actions, and they are also
known as functions.
To reuse code: define the code once, and use it many times.
Access modifier: Determines from where the method could be accessed. The three main
type of access modifiers:
These access modifiers are also used when declaring your data members, to control
access to them.
Return type: Tells you what type of data the method will return. This can include any of
your primitive data types or even an object type as well. We will discuss methods with
objects as return types and/or parameters in a later class. A method does not always
have to return a value, but since it is necessary to indicate a return type we use the
keyword void to indicate that the method will not return a value. When a method
returns a value, the last statement of the method will be the return statement that
indicates what the method will return. The following example will return a int value:
2
public int myMethod()
int ans x + y;
return ans;
Method name: must follow the naming convention of first word starts with a lowercase
letter and words adding to it must start with an uppercase letter. There are also no
spaces in the names of method. Example:
myMethod()
printTheAnswer()
Parameter list: This is also declared variables that indicate what the method must
receive to do what it is suppose to do. These variables will only be seen in the scope of
the method (between the opening and closing braces of the method). If more than one
parameter is defined, it must be separated by a comma. A parameter must be declared
just like any other variable but the syntax is different in that is does not have an access
modifier. Below is the syntax:
(<data type> <parameter name>, ….. , …… )
In the following example we have a method called addNumbers() that must receive two
integer numbers to add and will return the answer.
public int addNumbers(int num1, int num2)
{
int answer = num1 + num2;
return answer;
}
The value of the parameters is send when the method is called with the object. This
process is known as message passing. When we start creating objects of a class we will
discuss this topic in detail.
1.3 Constructor:
The constructor method is a special method that is part a class. The syntax of the constructor
method:
3
The constructor must always be declared public since it must always be accessible by other
classes.
The name of the constructor method must be the same name as the class name. For example: If
your class name was declared as MyClass then the constructor will look like this:
public MyClass()
The purpose of the constructor method is the initialize the object. This is actually known as a
default constructor. This means it is the assign default values to the data members of the class
when an object of the class is created.
Let say we have an ABook class with two data members called “author” of type String and
“isbn” of type String. When a user created an object of the class it must state what the values of
the object data members must be. You will see when we declare and initialize object that you
will call the constructor method to assign default values to the object and then the user can use
the set methods to assign their own values.
4
Because the data members of a class are private, you cannot assign or see the value of these
variables of your object from outside the calls.
The rule:
To access private data members of a class you must make use of public methods to
assign values to them or retrieve their values.
We use set methods to assign values to the private/public data members of a class. You will
have a set method for every data member of you class (private and public members). The
syntax for a set method:
public void set<name of data member>(<same data type as parameter> <a parameter
of the same type as the data member>)
{
}
Set methods will always be declared as public since they must be accessible from outside the
class.
They will always have a return type of type void, because they are used to assign a value to the
data member (that is why it receives a value).
The name of the set method will start with the word ‘set’ and then you add the name of the
data member, starting with a capital letter (naming convention).
The set method will always receive only one parameter. This parameter will be of the same
type as the data member.
In this example we created set methods for the data members of our ABook class.
5
public void setIsbn(String i)
{
isbn = i;
}
Note that you will assign the parameter value to the data member. So whatever value that was
received by the method will be assigned to the data member.
You will not have set methods for constant data members (members that are declared as final).
As set methods were used to assign values to the data members of the object, we will use get
methods to retrieve the values of the data members. The syntax for the get methods:
public <return type must be the same type as the data member> get<name of data
member>()
{
return <data member name>;
}
Get methods will always be public since they must be accessible from outside the class.
Get methods are used to return the values of a data member and because of that it must have
a return type. The return type of the get method will be the same as the type of the data
member.
The name of the get method will start with the word ‘get and then you add the name of the
data member, starting with a capital letter (naming convention).
There is always just one statement in a get method. It is the return statement that will return
the value of the data member.
In this example we created get methods for the data members of our ABook class.
6
isbn = “00000000000”;
}
Other than the constructor method, and get and set methods for all the data members, there
could be other methods in the class to specify a specific task. A method is used to group
together statements that must repeat, or in object-orientation, the functionality (behavior) of
an object is specified with methods. In other words, whatever an object can or must do will be
represented with methods.
Move the book around, like place it in your bag or on a shelf. (move())
We will add another data member called pages that will specify the number of pages
the book will have. Then there must be a method that will allow us to turn to a specific
page. (pageTo())
We will also add a data member called ‘contents’ that holds the contents of the book.
We will have a method that will add to the content of the book and return the content
again. (addContent())
7
The following code displays the complete ABook class:
import java.util.*;
public ABook()
{
author = "The author";
isbn = "00000000000";
pages = 0;
contents = "Content";
}
8
public String getIsbn()
{
return isbn;
}
9
1.7 UML class diagram:
The syntax in which methods are represented in a UML class diagram is shown below:
ClassName
Data members
<access modifier> <method name>(<parameter types>): <return type>
The access modifier is the same as for working with the data members in that it is a (+) for
public and a (-) for private.
The method name is name you want to give to the method. Must follow the coding
conventions.
The parameter list is showing only the data types of the parameters, separated by a comma.
Below is the full UML class diagram for the ABook class as created earlier.
ABook
- author: String
- isbn: String
- pages: int
- contents: String
+ ABook()
+ setAuthor(String): void
+ setIsbn(String): void
+ setPages(int): void
+ setContents(String): void
+ getAuthor(): String
+ getIsbn(): String
+ getPages(): int
+ getContents(): String
+ move(String): void
+ pageTo(int): void
+ publishDate(): GregorianCalendar
+ addContent(String): String
10
Activities
Create the following methods for the classes you already started when we did data members.
Person
- name: String Pizza
- surname: String - size: char
- id: String - type: String
- age: short - numberOfTopings: int
- height: double - base: char
- shoeSize: int + Pizza()
- gender: char + setSize(char): void
+ Person() + setType(String): void
+ setName(String): void + setNumberOfTopings(int): void
+ setSurname(String): void + setBase(char): void
+ setId(String): void + getSize(): char
+ setAge(short): void + getType(): String
+ setHeight(double): void + getNumberOfTopings(): int
+ setShoeSize(int): void + getBase(): char
+ setGender(char): void + buildPizza(): void
+ getName(): String + bake(int, int): void
+ getSurname(): String
+ getId(): String
+ getAge(): short
+ getHeight(): double
+ getShoeSize(): int
+ getGender(): char
+ walk(): void
+ talk(String): void
+ dateOfBirth(): void
+ putOnShoes(): void
11
IceCream
- name: String
- flavor: String
- price: double
+ VAT: double
+ liters: double
+ IceCream()
+ setName(String): void
+ setFlavor(String): void
+ setPrice(double): void
+ setLiters(double): void
+ getName(): String
+ getFlavor(): String
+ getPrice(): double
+ getLiters(): double
+ melt(): void
+ freeze(): void
12