Fundamentals 9 min read

Understanding Encapsulation in Java with Example Classes

This article explains the concept of encapsulation in Java, describing its purpose of hiding internal details, outlining four key benefits, and illustrating its use through Husband and Wife class examples, including getter/setter methods, validation, and how encapsulation simplifies future code modifications.

Java Captain
Java Captain
Java Captain
Understanding Encapsulation in Java with Example Classes

Encapsulation, literally meaning "packaging", is a form of information hiding that uses abstract data types to bundle data together with the operations that act on that data, exposing only authorized interfaces while keeping internal details private.

For an object, encapsulation means that it contains its own attributes and methods, allowing it to operate independently of other objects.

The four main benefits of encapsulation are:

Reduced coupling between components.

Freedom to modify the internal structure of a class.

Precise control over member access.

Concealment of implementation details.

Below are two example classes, Husband and Wife , demonstrating encapsulation with private fields and public getter/setter methods.

public class Husband{   
    /* 
     * Encapsulated attributes 
     * Name, sex, age, and wife are private properties of a person 
     */
    private String name ; 
    private String sex ; 
    private int age ; 
    private Wife wife; 
    
    /* 
     * getter() and setter() are the public interfaces of this object 
     */
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getSex(){
        return sex;
    }
    public void setSex(String sex){
        this.sex = sex;
    }
    public int getAge(){
        return age;
    }
    public void setAge(int age){
        this.age = age;
    }
    public void setWife(Wife wife){
        this.wife = wife;
    }
}
public class Wife{ 
    private String name; 
    private int age; 
    private String sex; 
    private Husband husband; 
    
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getSex(){
        return sex;
    }
    public void setSex(String sex){
        this.sex = sex;
    }
    public void setAge(int age){
        this.age = age;
    }
    public void setHusband(Husband husband){
        this.husband = husband;
    }
    public Husband getHusband(){
        return husband;
    }
}

The example shows that the Husband class does not provide a getter for the wife field, and the Wife class does not provide a getter for age , humorously illustrating that a husband "keeps his wife hidden".

Encapsulation makes an object's attributes private while offering controlled access through methods. Without any public methods, a class has little practical use—much like a house with no doors or windows; the private interior would be inaccessible.

If encapsulation is not used, fields are declared public, as shown in the following version of Husband :

public class Husband{ 
    public String name ; 
    public String sex ; 
    public int age ; 
    public Wife wife; 
}

Using this class directly would look like:

Husband husband = new Husband(); 
husband.age = 30; 
husband.name = "Zhang San"; 
husband.sex = "Male"; // redundant

When a change is needed—e.g., converting age from int to String —all client code would have to be updated. With encapsulation, only the setter method needs to change.

public class Husband { 
    private String name ; 
    private String sex ; 
    private String age ; // changed to String
    private Wife wife; 
    
    public String getAge(){
        return age;
    }
    public void setAge(int age){
        // conversion logic
        this.age = String.valueOf(age);
    }
    /** other getters/setters omitted */
}

Other code can continue to call husband.setAge(22) without modification.

Encapsulation also enables precise control over member values. For example, a setter can validate age to prevent impossible values:

public void setAge(int age){
    if(age > 120){
        System.out.println("ERROR: invalid age input...");
    } else {
        this.age = age;
    }
}

Similarly, encapsulation allows conversion of stored representations for presentation. The following getter translates a numeric gender code into a readable string, and another method generates HTML based on an object's status:

public String getSexName(){
    if("0".equals(sex)){
        sexName = "Female";
    } else if("1".equals(sex)){
        sexName = "Male";
    } else {
        sexName = "Other";
    }
    return sexName;
}

public String getCzHTML(){
    if("1".equals(zt)){
        czHTML = "
Enable
";
    } else {
        czHTML = "
Disable
";
    }
    return czHTML;
}

These examples demonstrate how encapsulation protects internal data, simplifies future modifications, and provides a clean interface for external code.

For further Java learning resources, you may join the Java study group QQ: 495273252.

JavaoopEncapsulationGetterSetterObjectOrientedProgramming
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.