05 Handout 1
05 Handout 1
ENCAPSULATION
Ex. public boolean isEnrolled() {
Fundamentals return status;
• Encapsulation describes the ability of an object to hide its }
data and methods. 4. Names of setter methods begin with set.
• Benefits of encapsulation: Ex. public void setName(String name) {
o It allows writing of reusable programs. this.name = name;
o It restricts access only to those features of an object }
that are declared public.
• In Java, a class encapsulates the fields, which holds the state Immutable Classes
of an object, and the methods, which define the actions of the • A class is considered immutable if it remains unchanged after
object. an object of another class is constructed.
• Fields are encapsulated by declaring instance variables as • For a class to be immutable, remove the setter methods and
private and methods as public. use the constructor for setting the values.
• An accessor or a getter method is a public method that Example:
returns data from a private instance variable. public class Student {
• A mutator or a setter method is a public method that changes private String name;
the data stored in one or more private instance variables. public Student(String name) {
Example: this.name = name;
public class Student { }
private String name; public String getName() {
public void setName(String name) { return name;
this.name = name; }
} }
public String getName() {
return name; References:
Savitch, W. (2014). Java: An introduction to problem solving and programming (7th ed.).
} New Jersey: Pearson Education, Inc.
} Oracle Docs (n.d.). Citing sources. Retrieved from
https://docs.oracle.com/javase/tutorial/java/javaOO/index.html
Rules in Implementing Encapsulation
1. Instance variables are declared private.
Ex. private String name;
2. Names of getter methods begin with get if the property is not
a boolean.
Ex. public String getName() {
return name;
}
3. Names of getter methods begin with is if the property is a
boolean.