Department of Computer Science: HCT216: Programming 2
Department of Computer Science: HCT216: Programming 2
HCT216: Programming 2
Unit Outline
• Methods: arguments, return types
• Method overloading
• The static keyword
• Constructors
• Access modifiers
• Encapsulation
• Passing parameters to methods
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
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
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
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
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
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)
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
END