Learn Java - Access, Encapsulation, and Static Methods Cheatsheet - Codecademy
Learn Java - Access, Encapsulation, and Static Methods Cheatsheet - Codecademy
Encapsulation
Encapsulation is a technique used to keep
implementation details hidden from other classes. Its aim
is to create small bundles of logic.
Accessor Methods
In Java, accessor methods return the value of a private
variable. This gives other classes access to that value public class CheckingAccount{
stored in that variable. without having direct access to the private int balance;
variable itself.
Accessor methods take no parameters and have a return
//An accessor method
type that matches the type of the variable they are
public int getBalance(){
accessing.
return this.balance;
}
}
Mutator Methods
In Java, mutator methods reset the value of a private
variable. This gives other classes the ability to modify the public class CheckingAccount{
value stored in that variable without having direct access private int balance;
to the variable itself.
Mutator methods take one parameter whose type
//A mutator method
matches the type of the variable it is modifying. Mutator
public void setBalance(int newBalance){
methods usually don’t return anything.
this.balance = newBalance;
}
}
Local Variables
In Java, local variables can only be used within the scope
that they were defined in. This scope is often defined by a public void exampleMethod(int
set of curly brackets. Variables can’t be used outside of exampleVariable){
those brackets. // exampleVariable can only be used
inside these curly brackets.
}
Static Methods
Static methods are methods that can be called within a
program without creating an object of the class. // static method
public static int getTotal(int a, int b) {
return a + b;
}
System.out.println(Math.pow(5, 3)); //
Prints: 125.0
System.out.println(Math.sqrt(52)); //
Prints: 7.211102550927978
}
Methods with Static Variables
Both non-static and static methods can access or change
the values of static variables. class ATM{
// Static variables
public static int totalMoney = 0;
public static int numATMs = 0;
public int money = 1;