Access, Encapsulation, and Static Methods Cheatsheet
Access, Encapsulation, and Static Methods Cheatsheet
Encapsulation
Encapsulation is a technique used to keep
implementation details hidden from other
classes. Its aim is to create small bundles of
logic.
Mutator Methods
In Java, mutator methods reset the value of a public class CheckingAccount{
private variable. This gives other classes
private int balance;
the ability to modify the value stored in that
variable without having direct access to the
variable itself. //A mutator method
Mutator methods take one parameter whose
public void setBalance(int
type matches the type of the variable it is
modifying. Mutator methods usually don’t return newBalance){
anything. this.balance = newBalance;
}
}
Local Variables
In Java, local variables can only be used within public void exampleMethod(int
the scope that they were defined in. This scope
exampleVariable){
is often defined by a set of curly brackets.
Variables can’t be used outside of those // exampleVariable can only be used
brackets. inside these curly brackets.
}
The this Keyword with Variables
In Java, the this keyword can be used to public class Dog{
designate the difference between instance
public String name;
variables and local variables. Variables with
this. reference an instance variable.
public void speak(String name){
// Prints the instance variable
named name
System.out.println(this.name);
System.out.println(Math.sqrt(52)); //
Prints: 7.211102550927978
The static Keyword
Static methods and variables are declared as public class ATM{
static by using the static keyword upon
// Static variables
declaration.
public static int totalMoney = 0;
public static int numATMs = 0;
// A static method
public static void averageMoney(){
System.out.println(totalMoney /
numATMs);
}
// A static method
public static void averageMoney(){
System.out.println(totalMoney /
numATMs);
}
}
Static Methods with Instance Variables
Static methods cannot access or change the class ATM{
values of instance variables.
// Static variables
public static int totalMoney = 0;
public static int numATMs = 0;
// A static method
public static void averageMoney(){
// Can not use this.money here
because a static method can't access
instance variables
}
// A non-static method
interactingwith a static variable
public void nonStaticMethod(){
totalMoney += 1;
}
}
Static Methods and the this Keyword
Static methods do not have a this reference public class DemoClass{
and are therefore unable to use the class’s
instance variables or call non-static methods.
public int demoVariable = 5;
}
public static void demoStaticMethod()
{
// Can't use "this.demoVariable" or
"this.demoNonStaticMethod()"
}
}
Print Share