OCA Exam Preparation: Methods - Review
OCA Exam Preparation: Methods - Review
METHODS – REVIEW
ABBREVIATIONS & ACRONYMS
The structure of Java method declaration (left to right in the stated order unless noted otherwise):
an access modifier such as public, protected or private;
interface method modifier default (can be combined – redundantly – with public only)
an optional specifier such as abstract, final or static (NB: final and static may be combined);
optional specifier(s) may precede access modifier;
the return type such as void or another valid data type;
the method name, which is just another Java identifier, followed by a matching pair of parentheses to
contain an optional list of the method parameters;
if the parameters list is present, each parameter must be specified by its data type (which can be a
primitive or reference type) and its name;
unlike multiple variable declaration where we can state the data type just once if all the variables are of
the same type, each method parameter must have its own data type specified explicitly;
parameter declarations are separated by commas;
after the closing parenthesis comes an optional list of exception types, which starts with throws;
unlike the catch block where a narrower exception type must appear before a wider type, the exception
types thrown by the method may be declared in any order;
the body of any method must be enclosed by a pair of matching curly braces;
EXTRA: the method body can be completely empty or contain any number of the empty statements, that
is, semicolons.
5
OVERLOADING & PASSING VALUES, cont’d
Only a single vararg is permitted in the list of parameters per method declaration; more than
that, the vararg, when present, must be the last variable among the declared parameters.
Methods that do not return a value (void methods):
the body of such methods may contain an empty return statement, in other words, a
return stat that is not followed immediately by a variable or literal;
Methods that return a value:
their bodies must contain a return stat immediately followed by an appropriate value…
… which is passed back to the caller…
… who may elect to disregard it altogether or assign it to a variable. If such is the case,
the var’s type must be compatible with the returned value’s type.
The return statement, when present, must be the last statement in the method body:
public void doStuff(){
return; // VALID although redundant
// ; // harmless but INVALID because unreachable
}
6
OVERLOADING & PASSING VALUES, cont’d
7
OVERLOADING & PASSING VALUES, cont’d
8
6.2 & 6.4
& 6.5
static KEYWORD
USING ACCESS MODIFIERS
ENCAPSULATION
9
static, ACCESS MODS, ENCAPSULATION
The static modifier is valid with variables, methods and initers but cannot be applied to the
top-level classes and interfaces.
static fields are shared by all instances of a given class.
Since static fields and methods belong to the class, they can be accessed even without
instantiating it first. When referenced from outside the class, they are called by using the class
name, e.g. java.lang.Math.PI or Math.random().
A static method may not call non-static variables or methods while the opposite is
permitted. The exam tests us on at least three variants of this aspect:
a static method accessing an instance var,
a static method calling a non-static method, and
a non-static method either accessing a static field or invoking a static method.
Java allows to import static members by using the keywords import static.
A method cannot be declared both abstract and static.
EXTRA: The static methods defined in classes are inherited although they do not take
part in polymorphism. The static methods defined in interfaces aren’t inherited.
10
static, ACCESS MODS, ENCAPSULATION, cont’d
The access modifiers control the accessibility of a given class and its members from outside
the class and its package:
the public keyword means that the code is accessible from anywhere;
the protected keyword means the code is accessible by the classes or interfaces inside the same
package or by the derived data types;
Known trap on the exam: An attempt by a class instantiated outside its package to access
its own protected member.
the default (a.k.a. package-private) access is denoted by the absence of any access modifier and
means that the code is accessible only from within the same package;
Known trap on the exam: An attempt to access a class defined using default access from
outside its package.
the private keyword means the code is visible only inside the same class.
Known trap on the exam: A subclass attempting to access a private member of its
superclass.
Combat versions: A non-public class can’t be accessed from outside its package.
protected members of a parent in a diff pack aren’t accessible
to the child whose reftype is Parent. 11
static, ACCESS MODS, ENCAPSULATION, cont’d
EXTRA: A static method invoked on a null object doesn’t throw an NPE (because the
object isn't used in any way):
class Test{
static void test(){ System.out.println("Hi!"); }
public static void main(String[] args) {
Test t = new Test();
t = null;
t.test(); // Hi!
}
}
12
6.3
CONSTRUCTORS
13
CONSTRUCTORS
14
CONSTRUCTORS, cont’d
A class can have multiple constructors. Just like regular methods, they are overloaded by using
different lists of arguments.
Overloaded constructors invoke each other by using the keyword this(), which should be the
first stat in the caller’s body.
Corollaries: A constructor may not call another constructor by using its class name.
An attempt by a regular method to use this() will cause a comperr.
Constructors can differentiate between their arguments and instance vars by prepending the
instance var’s name with the keyword this followed by a dot.
EXTRA: Constructors can declare local variables (whose scope is therefore limited to the
constructor), which will shadow the similarly named fields.
EXTRA: Polymorphisms extends to the constructors, too.
16
CONSTRUCTORS, cont’d
EXTRA: Constructors can throw exceptions. The exception-wise rule in ctors, however, is
opposite to what we have for methods. Note that just like in the case of method overriding, this
rule doesn’t involve RTEs:
1 class A {
2 A() throws IOException {}
3 A(int a) throws IOException {}
4 A(double d) throws IndexOutOfBoundsException {}
5 }
6
7 class B extends A{
8 B() throws FileNotFoundException {
9 super(); // INVALID
10 }
11 B(int b) throws Exception { super(1);}
12 B(double d) throws ArrayIndexOutOfBoundsException { super(1.0); }
13 }
14
15 class C extends A{
16 C() throws FileNotFoundException { // INVALID
17 try {
18 super(); // INVALID
19 }
20 catch(IOException ioe){}
21 } 17
22 }
CONSTRUCTORS, cont’d
Although constructors routinely function as initializers, a class can define separate initializer
blocks, which can be either static or non-static.
An initializer block can declare local vars, access both static and instance fields or call static
and non-static methods (the rule of non-static entities in static context still applies), define
loops, conditional and TCF constructs.
The order of precedence when instantiating a class:
static initers for the entire inheritance chain; it is done only once;
instance initers for the superclass;
superclass constructors;
instance initers for the subclass;
subclass constructors.
Corollaries: Instance initers run for every object that is being created.
Constructors run after all other initers within the same class.
Both static and instance initializer blocks are executed in the order they appear.
18
CONSTRUCTORS, cont’d
EXTRA: static initers of a class are not executed unless you access something that belongs to
this particular class.
Corollary: Simply declaring a refvar isn’t enough for static initers start running.
final non-local vars must be inited even if they are never used:
class Test {
int a;
// final int b; // INVALID
void run(){ final c; }
}
Where and how this initing is done depends on whether the var is static or not:
final instance vars can be inited in THREE places:
o at the point of declaration,
o in instance initers, and
o in constructors.
final static vars can be inited in TWO places only:
o at the point of declaration, 19
o in static initers.
CONSTRUCTORS, cont’d
Pay attention:
final static vars can’t be inited in ctors or instance initers:
class Test {
final static String str;
static{ str = "Hello"; }
Test{ str = "Goodbye"; } // INVALID
}
Sidenote: In the preceding example, the compiler complains of an attempt to modify a final
var. If we comment out the static initer, the compiler produces yet another misleading error
message: "variable str not initialized in default constructor“, which is impossible in the first
place:
class Test {
final static String str; // becomes VALID when we add Test(){}
Test(){} // ... and comperr moves to this LOC!
}
Here the error message on the line that defines the no-arg constructor quite correctly says
that "variable str might not have been initialized".
20
CONSTRUCTORS, cont’d