0% found this document useful (0 votes)
35 views21 pages

OCA Exam Preparation: Methods - Review

Uploaded by

carutsa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views21 pages

OCA Exam Preparation: Methods - Review

Uploaded by

carutsa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

OCA Exam Preparation

METHODS – REVIEW
ABBREVIATIONS & ACRONYMS

actype – actual object’s type at run time AIOOBE – ArrayIndexOutOfBoundsException


assop – assignment operator CCE – ClassCastException
castype – data type specified inside the parens for an explicit cast ChE – checked exception
comperr – compilation error CSR – the Catch-or-Specify Requirement
ctor – constructor DTPE – DateTimeParseException
dim – dimension E – an exception (regardless of the type)
initer – initializer IAE – IllegalArgumentException
op – operator IOE – IOException
paramlist – list of formal parameters in a lambda expression IOOBE – IndexOutOfBoundsException
preditype – data type specified inside the angle brackets LDT – any of the new date/time classes in Java 8
reftype – reference type LOC – line of code
refvar – reference variable NFE – NumberFormatException
sout – any printing statement such as System.out.println(), etc. NPE – NullPointerException
stat – statement RTE – RuntimeException
ternop – ternary operator SIOOBE – StringIndexOutOfBoundsException
var – variable TCF – try-catch-finally construct

Igor Soudakevitch  2019 2


[email protected]
EXAM OBJECTIVE’S STRUCTURE

The 1Z0-808 topics within this group:


1. Create methods with arguments and return values, including overloaded methods;
2. Apply the static keyword to methods and fields;
3. Create and overload constructors, including impact on default constructors;
4. Apply access modifiers;
5. Apply encapsulation principles to a class;
6. Determine the effect upon object references and primitive values when they are
passed into methods that change the values.

Source: Oracle Univ. 3


6.1 & 6.6
OVERLOADING METHODS
PASSING VALUES
4
OVERLOADING & PASSING VALUES

 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

Known traps on the actual exam:


 the return type and method name are separated by an access modifier or optional
specifier;
 more then one vararg is defined in the list of parameters;
 the vararg isn’t the last one in the list of parameters;
 the method body is missing a return stat although the method is declared as non-
void;
 return is followed by some other – therefore unreachable! – stats;
 what return delivers is inconsistent with the method declaration (incompatible data
types);
 methods differ only in their return types and, therefore, are not overloaded →
comperr.

7
OVERLOADING & PASSING VALUES, cont’d

 Overloaded methods differ in their lists of formal parameters.


Corollary: An attempt to define multiple methods that differ only in their access modifiers,
optional specifiers, return types, or thrown exceptions will cause a comperr.

 Learn by heart: In case of overloading, exact matches are used first…


… followed by wider primitives…
… then by autoboxing…
… and finally by varargs.
 Since Java uses pass-by-value, calling a method creates copies of its params  used as args.
Corollaries: When a primitive is passed to a method, its value never changes for the caller.
When an object reference is passed to a method, changes in the object’s state
might be reflected for the caller unless the called method assigns a new object
reference to the passed-in argument before modifying its field(s).
Other wording: invoking a method on a passed-in object can potentially
change it.

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

 Encapsulation prevents callers from modifying the instance variables directly.

 Encapsulation is implemented by making instance vars private while providing public


getters and/or setters.

 Properly encapsulated class exposes its state through methods.

 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

 Constructors do NOT ‛construct’ objects: they initialize them.


 Constructors resemble methods (e.g., they accept arguments, can be overloaded and may throw
exceptions that require handling in the TCF constructs) but they don’t specify a return type, not
even void. In addition, ctors must share the same name with their class.
Known trap on the exam: As soon as a would-be constructor specifies a return type, the
compiler stops treating it as a constructor even though it shares
the same name with the class → whenever you think you see a
constructor, double check it’s not a method.
 A default, no-arg ctor is implicitly declared in the class that doesn’t define any ctor explicitly.
Known traps on the exam: The default constructor is the one that is provided automatically by
the compiler → even if an explicitly defined constructor specifies
no arguments, it cannot be called the default constructor.
Whenever superclass has no-arg ctor apart from other ctors, explicit call to an appropriate parent
ctor must be provided in the child’s constructors whose bodies
don’t start with this().

14
CONSTRUCTORS, cont’d

 The default constructor has the same accessibility as the class.


Corollary: Since the humanware-defined no-arg constructor isn’t the default one, the
above rule doesn’t apply to it. ← known trap on the exam
Combat rule: Different packages? Watch out! If Parent defines a package-private no-arg
ctor, Child won’t be able to access it:
package one;
public class One { One(){} } // ctor is neither public
// nor protected
package two; Another Illustration
// class Two extends one.One { } // GAME OVER

 EXTRA: Constructors are not inherited.


 Constructors accept access modifiers only.
Corollary: Unlike regular methods, constructors may not be declared abstract,
static or final.
 A matching pair of parentheses is mandatory for a constructor.
15
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

Putting this rule out in code:


class Test {
final static int a, b;
final int c, d;
{
a = 10; // INVALID: since a is static, it must be
} // available always, while instance intiters
// run only when we ask to create an object;
// also note that the comperr, however, is
// about an attempt to change a final var
static { b = 10; a = 10; }
static {
c = 10; // INVALID: non-static in static context
}
{ c = 10; }
Test(){
b = 10; // INVALID: b is static while constructors
// run only when we are creating objects;
// comperr is again about b being final...
d = 10;
} 21
}

You might also like