Java Encapsulation
Java Encapsulation
Encapsulation
The meaning of Encapsulation, is to make
sure that "sensitive" data is hidden from
users. To achieve this, you must:
The get method returns the variable value, and the set method
sets the value.
Syntax for both is that they start with either get or set,
followed by the name of the variable, with the first letter in
upper case:
Example
Example explained
public class Person { The get method returns
private String name; // private =restricted
the value of the
access
variable name.
// Getter The set method takes a
public String getName() { parameter (newName) and
return name; assigns it to
} the name variable.
The this keyword is used
// Setter to refer to the current
public void setName(String newName) { object.
this.name = newName; However, as the name variable is
} declared as private,
we cannot access it from outside
} this class:
Example
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
However, as
myObj.name = we try to access a private variable, we get an error:
"John";
System.out.println(myObj.name);
} MyClass.java:4: error: name has private access in Person
myObj.name = "John";
} ^
MyClass.java:5: error: name has private access in Person
System.out.println(myObj.name);
^
2 errors
If the variable was declared
as public, we would expect the
following output: John
Instead, we use the getName() and setName() methods to access and
update the variable:
Example
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Constructor // Constructor
public Person(String name, int age) { public Person(String name, int age) {
this.name = name; this.name = name;
this.age = age; this.age = age;
} }
// Getter method
public String getName() {
return name;
}
// Setter method
public void __________(String name) { 1.
this.__________ = __________; 2.
}
}
Complete the getter method for the age field:
// Setter method
public void setAge(int age) {
this.age = age;
}
// Getter method
public __________ getAge() { 3.
__________ __________; 4.
}
}
Fill in the blanks to complete both getter and setter
methods for the salary field.
// Getter method
public __________ getSalary() { 5.
return __________; 6.
}
// Setter method
public void __________(double salary) { 7.
this.__________ = __________; 8.
}
}