Skip to content

Encapsulation Example. Austin Alcoser

aalcoser45 edited this page Jan 21, 2015 · 4 revisions

Encapsulation is the process of creating private variables thus hiding their values from outside classes, however they are accessed through public methods within the same class. Through this concept, a class can have full control over what is in its variables.

Example:

public class EcapExample {

private String middlename;

private int age;

private String hobby;

public int getAge() {

return age

}

public String getMiddlename() {

return middlename;

}

public String getHobby() {

return hobby;

}

public void setAge(int newAge) {

age = newAge();

}

public void setMiddlename(String newMiddlename) {

middlename = newMiddlename();

}

public void setHobby(int newHobby) {

hobby = newHobby();

}

public class runEcapExample {

public static void main(String[] args){

EcapExample ecap = new EcapExample();

ecap.setage(18);

ecap.setmiddlename("Wade");

ecap.sethobby("Videogames");

System.out.println("Middle name: " ecap.getMiddlename() + " Age: " + ecap.getAge()); } }