Show Menu
Cheatography

Java Methods and encapsulations Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Accessors

private
class private
(default)
package private
protected
package privat­e+s­ubclass
public
any class

Optional specifier

static
class method­,ac­cessed by class name or obj reference
abstract
w/o body, even empty {}
final
no overridden by subclass
synchr­onized
OCP, thread safe
native
interact with other language
strictfp
float point calc portable

Return type

Required
void =return; or no return statement
void method­(){­ret­urn;}
void method(){}
String method­(){­return "­";}
String method­(){­return null;}
String[] method­(){­return null;}
Integer method­(){­return null;}
void method­(){­return null;}
This not compiled
String method­(){if ... return null; else return;}
Not compile

Method name

follow variable naming rule
start with
letters, &, _
can contains
number
Can not start with number

Parameter list

Must have a parameter list
if no parameter, use empty ()
parameter separated by ;

Optional Exception List

throws excapt­ion­_na­me1­,ex­cep­tio­n_n­ame­2,...

Method body

MUST for all non abstract method, Could by empty {}
abstract method could not have a body, even empty {} one

Order must be followed

accessor --opti­ona­l-m­odifier -- return type name() option­al-­throws .... {}
accessor could be omitted for default access
access­or,­return type, name, (), {} are required
signature: return type + name + ()
overlo­ading: same name, but differs in parameter list, overlo­ading won't care about return type
 

varargs

//varargs=variable arguments,
//array but variable in length
//only last one parameter could be varargs
//accessed like array
public void walk (int start, int...steps)
{ System.out.print(steps.length +"," +steps[0]);}
walk(1);//ArrayIndexOutOfBoundsException
walk(1,2) //1,2
walk(1,2,3);//2,2
walk(1,null);//NullPointException
walk(1,new int[] {1,2,3}); //3,1
walk(1,new int[3]); //3,0

protected members

pacakage
subclass
direct access
by obj ref
same
Yes
yes
yes
same
No
yes
Yes
diff
Yes
yes
No *
diff
diff
No
No
could access protected member from parent by obj ref of subclass itself

Design static methods and fields

2 use cases
shared component among instances
util/h­elper which not require any obj state
2 calling approaches
by class name
by obj ref ( null obj can too)
Static variables
Counter, Constant
Static initia­lizer- run once
static {....}­//bad practice
import static java.u­til.Ar­ray­s.a­sList
import static java.u­til.Ar­rays.*;
static import java.u­til.Ar­rays.*;
syntax error
import static java.u­til.Ar­rays;
Can not static import class
Name conflicts: not compiled
Solution: regular import,ref by classname
Object has its status, but shared the code, and static data

Static vs instance

type
calling
legal
how
static method
static
Yes
Class name
static method
instance
No
create obj
instancd method
static
Yes
class name,obj ref
instance method
instance
Yes
obj ref
Object has its status, but shared the code, and static data

Passing data among method

pass by value
change in callee not affect caller
pass by ref
change in callee do affect caller
Return value, if not used, will be discarded.
 

Overlo­ading a method

Method signature
name+p­ara­meter list
Overlo­ading:
same name+d­iff­erent parameters
varargs
2nd test can't compile, varargs and array = same parameter list
 
void test(i­nt... a){}; void test(int[] a){}
 
test(new {1,2,3}) call either
 
test(1­,2,3) call test(i­nt... a) only
autoboxing
void fly(int a){}; void fly(In­teger a){};
 
fly(3) call fly(int a); if not exit, call fly(In­teger a)
Ref type
void fly(Object o){};
 
fly(3)­:match fly(int) >fl­y(I­nteger) >fl­y(O­bject o)
Primitive
autoca­st(­wider), explicitly cast(n­arr­ower)
overlo­ading matching order
exact match -> unwrapping -> promotion -> wrapping ->v­ara­rgs­(exact match, promotion, wrapper)
promotion is an indepe­ndent check, it retains no influence over wrapping check
void play(Long l){}
play(4); compile error, 2 step conver­sion, only 1 conversion allowed, play(4L) will work.

Create constr­uctors

Same name as class
no return type
default no-arg­ument constr­uctor
auto generated if no constr­uctor provided
overlo­ading of constr­uctor
Constr­uctor chain
by this(...)
Calling Constructor
This(...): not in static method
first line of method
 
new Constr­uct­or(...)
Create new object
final field
must be initia­lized by the time of constr­uctor completion
super()
call automa­tically in any constr­uctor implicitly
 
all class are subclass of Object
order of initia­liz­ation
super() is always call in every constr­uctor implic­itly; super(...) must be called explicitly
super() ->s­tatic declar­ation and static {} as its order ->i­nstance declar­ation and {} as its order ->c­ons­tructor
example
class Bunny{ }
public bunny(){}
wrong
 
public Bunny(){}
OK
 
public void bunny(){}
OK
 
public void Bunny(){}
wrong

Encaps­ulating data

Encaps­ula­tion: binding fields with method; data hiding­(hiding proper­tie­s+i­mpl­eme­ntation details): private fields­+public setter and getter; purpose: data validation and integrity + flexib­ility code for upgrade and mainte­nance
private attributes
public getter(), setter(), isA()
Immutable class
Math, String
Class w/o public setter
no status change of object once created
safe to passing around and easy to maintain
bette perfor­mance by limiting the number of copies ( string pool)
String and String­Buffer
Mutated by String­Buffer, return a String
JavaNean
a class with no-arg­ument constr­uctor
naming conven­tio­n:i­nstance variable, getA,s­etA­,isA,
reusable
easy to code

Lambdas expression

Why lambdas?
less code
delayed implem­ent­ation
declar­ative
what's lambdas?
a declar­ative block of code
passed to the associated 1 method interface, as delayed dynamic implement the method
Syntax
parameter
->
body
()->true
simplest format
a->­a.c­anHop()
type is optonal
(Animal a) ->{­return a.canH­op();}
can't miss ; or return if use{}; need () if has type
(a,b)-­>a.c­an­Hop()
() required if >1args; if >1 statement, need {}
Context
functional method to match the only method of an interface
 
replace the implem­enting class of the interface
 
parameter type will be get from the associated interface API
Notes
lambdas expr could access static­/in­stance variable. method parameter and local variable also fine if not assigned a new value
can not redeclare a variable same name as local variable
(a,b)-­>{int a=0;return 5;}
won't compile

Lambdas example - Predicate

//Predicate interface
public interface Predic­ate­<T>{
    boolean test(T t); }

//
class Animal{
  private String canHop;
  public void setCanHop(boolean b)
  {    canHop =b; }
  public boolean canHop()
  {    return canHop; }
}
public interface CheckTrait
 {   boolean test(Animal a); }
public class CehckIfHopper implements CheckTrait{
   public boolean test(Animal a)
  { return a.canHop();} 
}

//compare 
import java.util.function.Predicate;
public class TestLambdas {   
   public static void main(String[] args){
     Animal a1 = new Animal();
     a1.setCanHop(true);
     print (a1,a->a.canHop()); 
     // print2 (new checkIfHopper());
   }
   void print(­Animal a, Pre­dicate<Animal> p) {
      if (p.tes­t(a) {} }

   void print2(­Animal a, CheckTrait c) {
      if (c.tes­t(a) {} 
}
//for Predicate version, no interface and implementing class needed
// {return a.canHop();} will be delayed dynamic implementation of test method in Predicate interface.
Type must match in lambda expr, or just do put type

Lambdas - ArrayL­ist.re­mov­eIf()

//Java 8 intergrated Predicate interface into ArrayList
default boolean removeIf(Predicate<? super E> filter)

arrayList.removeIf(s->s.charAt(0)!='h');
ArrayL­ist­<? super E> : super class of E, upper bound: "This can be cast to E".
ArrayL­ist­<? extends E>: hold type= subclass of E, lower bound: "E can be cast to this."
ArrayL­ist< E>: holder type E

What happens after new Constr­uctor()

1. allocate memory space on the heap
2. create the object and instance variables are initia­lized with default value
3. explicit initialize the instance variabls
4. constr­uctor code are executed
Notes:­static variable are initia­lized once for all objects to be created, so it is before step 2
for no argument constr­uctor, super() is called first for initia­liz­ation