University of Zimbabwe
Department of Computer Science
HCT216: Programming 2
Unit 4 : Methods & Encapsulation
Lecturer: Gibson Mukarakate
Unit 1: Methods & Encapsulation
Unit Outline
• Methods: arguments, return types
• Method overloading
• The static keyword
• Constructors
• Access modifiers
• Encapsulation
• Passing parameters to methods
HCT216: Programming 2 (Java) Gibson Mukarakate 2
Unit 1: Methods & Encapsulation
Methods
• A method declaration comprises of:
1. Access modifier : optional
2. Specifier : optional
3. Return type : mandatory
4. Method name : mandatory
5. Parameter list : mandatory (can be empty)
6. Exception list : optional
7. Method body : mandatory (can be empty)
• The above components are explained in more
detail
HCT216: Programming 2 (Java) Gibson Mukarakate 3
Unit 1: Methods & Encapsulation
Methods: Access modifiers
• Can be:
1. public : can be called from any class
2. private : can be called only from within class
3. protected : can be called only from the same
class, package; and sub-classes
4. (not specified) / (default) : can be called only
from same class and same package. Also called
package private access
HCT216: Programming 2 (Java) Gibson Mukarakate 4
Unit 1: Methods & Encapsulation
Methods: Specifiers
• Can be:
1. static: used for class methods
2. abstract: used when doing a method declaration
only
3. final: for stopping sub-classes from overriding
the method
4. synchronized: for concurrent programming
5. native: for interacting with non-Java code
6. strictfp: for portability of floating-point
calculations
HCT216: Programming 2 (Java) Gibson Mukarakate 5
Unit 1: Methods & Encapsulation
Methods: return type
• Used to return values after a method
completes execution
• Any Java primitive type, reference types can
be returned
• If method does not return anything, void is
used
• Returned values must match specified type
• Java supports only one return value
HCT216: Programming 2 (Java) Gibson Mukarakate 6
Unit 1: Methods & Encapsulation
Methods: method name
• May only contain letters, numbers, $ and _
characters
• Should start with lowercase and use camel
case; as a convention
HCT216: Programming 2 (Java) Gibson Mukarakate 7
Unit 1: Methods & Encapsulation
Methods: parameter list
• Enclosed by parentheses; and multiple parameters are
separated by commas
• May be empty
• Can use varargs (variable arguments)
• Varargs must be the last in the parameter list; and a
method can only have one vararg, e.g.
public int add(int i, int … numbers) {}
Can call the above using:
add(5)
add(5, 1, 2)
add(5, new int[] {1,2,3})
• vararg list is basically treated like an array
HCT216: Programming 2 (Java) Gibson Mukarakate 8
Unit 1: Methods & Encapsulation
Methods: exceptions list
• Optional, and multiple exceptions are
separated by commas
• Used to indicate that something has gone
wrong (and what has gone wrong)
HCT216: Programming 2 (Java) Gibson Mukarakate 9
Unit 1: Methods & Encapsulation
Methods: method body
• Mandatory, but can be empty
• Empty for abstract methods, with a
declaration only, and having no
implementation
HCT216: Programming 2 (Java) Gibson Mukarakate 10
Unit 1: Methods & Encapsulation
The static keyword
• Used for class members: both methods and
fields
• They are referenced / “called” without
creating an instance
• Mainly used for:
i. Helper / utility methods that do not to access
instance state
ii. For state shared by all objects of a class
HCT216: Programming 2 (Java) Gibson Mukarakate 11
Unit 1: Methods & Encapsulation
The static keyword
• Static members are called by either using the class name or
any reference of the class, e.g.
public class Customer {
static int counter;
}
…
Customer.counter; // legal
Customer c = new Customer();
c.counter; // legal
c = null;
c.counter; // legal … and no NullPointerException thrown
• Note! They can even be called from null references
• Static methods cannot call instance methods
HCT216: Programming 2 (Java) Gibson Mukarakate 12
Unit 1: Methods & Encapsulation
static variables and initialisation
• Some static variables can change, e.g.
static int counter = 0;
• However, some must be constant for ever. For those,
the final keyword is used, e.g.
static final int maxCustomers = 500;
• It is possible to delay initialisation of static variables,
using static blocks; but not ordinary methods
• Also note that methods of static variables can be
called, even if they modify parts of the static variable,
e.g.
static final java.util.ArrayList myList;
myList.add(“John”);
HCT216: Programming 2 (Java) Gibson Mukarakate 13
Unit 1: Methods & Encapsulation
Static imports
• Used to import and use static members within
code, e.g.:
import java.util.Date;
import static java.util.Arrays.sort;
public class Test {
….
sort(myArray);
}
• Cannot be used to import classes or non-static
members
• Good for brevity, but not good for code
readability
HCT216: Programming 2 (Java) Gibson Mukarakate 14
Unit 1: Methods & Encapsulation
Passing data in Java
• Java uses pass-by-value semantics
• This means a calling method is given a copy of
the data; not the “reference” type. Any re-
assignment will not change the passed
reference
• Other languages use pass-by-reference
• Be careful to note when a reference type is
passed; as shown on next slide
HCT216: Programming 2 (Java) Gibson Mukarakate 15
Unit 1: Methods & Encapsulation
Passing data in Java
public static void testPassByValue(int i, int[] ia, ArrayList<Integer> list) {
i = 5;
ia[1] = 5;
list.add(0, new Integer(5));
}
public static void main(String[] args) {
int i1 = 2;
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(2);
int[] ia1 = {1,2,3};
testPassByValue(i1, ia1, list1);
System.out.println(i1);
System.out.println(ia1[1]);
System.out.println(list1.get(0));
}
• What are the values that will be printed ?
• Answer: 2, 5 and 5
HCT216: Programming 2 (Java) Gibson Mukarakate 16
Unit 1: Methods & Encapsulation
Method overloading
• Overloading happens when the same method
name is used for different methods in the
same class, e.g. :
public int add(int x, int y)
public double add(double d1, double d2)
public Double add(Double d1, Double d2)
• It is done by using different parameters. It
cannot be done with different return types or
access modifiers or the exception list
HCT216: Programming 2 (Java) Gibson Mukarakate 17
Unit 1: Methods & Encapsulation
Method overloading
• Note the following about overloading:
i. For varargs, remember a vararg is treated as an
array
ii. For autoboxing, the most specific method is
used
iii. For primitives, the most specific match is also
used first
HCT216: Programming 2 (Java) Gibson Mukarakate 18
Unit 1: Methods & Encapsulation
Constructors
• A constructor is basically a method with the same
name as the class; and has no return type
• Calling it returns an instance of the class. Thus it
is used to create instances of a class
• If no constructor is provided, a default
constructor is provided (at compile time): with
the following characteristics:
i. Has no parameters
ii. Has the public access modifier
iii. Has an empty body
HCT216: Programming 2 (Java) Gibson Mukarakate 19
Unit 1: Methods & Encapsulation
Constructor overloading
• Constructors can be overloaded just like ordinary
methods
• This results in the need for a constructor to call
another
• public Customer()
• public Customer(String name, String surname)
• Inside the one with parameters:
public Customer(String name, String surname) {
this(); // will call constructor & set fields for object
// Customer() // this will not set object values
}
• When using this, it must be the first statement in the
constructor
HCT216: Programming 2 (Java) Gibson Mukarakate 20
Unit 1: Methods & Encapsulation
Object creation: Order of initialisation
• There is an order in which various members of
a class are initialised:
1. The superclass of the class. Will be discussed
later under inheritance
2. Static variable declarations and static initialisers
in the order they appear in the file.
3. Instance variable declarations and instance
initialisers in the order they appear in the file.
4. The constructor
HCT216: Programming 2 (Java) Gibson Mukarakate 21
Unit 1: Methods & Encapsulation
Data encapsulation
• It is one of the tenets of object-oriented languages
• Basically done by
1. Making all instance fields private
2. Creating getters and setters that are used for accessing field
values
public class Test {
private String name;
public String getName() { return this.name}
public void setName(String name) {
this.name = name;
}
}
• Desired access to fields can be further controlled by the
access modifiers for the getters and setters
HCT216: Programming 2 (Java) Gibson Mukarakate 22
Unit 1: Methods & Encapsulation
END
HCT216: Programming 2 (Java) Gibson Mukarakate 23