Using private and public as appropriate for encapsulation

Ok, well this part of the SCJP syllabus overlaps with what I’ve written on Encapsulation but I can reuse my class so this should be a cheap post 🙂

In simple terms, if a field or method is public other classes can happily depend on them being there. Private fields and methods are not available to other classes and, as long as the public methods retain their functionality, other classes will be unaffected by changes to them. This is what we want from encapsulation… and also how we achieve it.

Here is our Person class from my post on encapsulation:

public class Person {
  // in this implementation we store both fields as is.
  private final String firstName;
  private final String lastName;
  public Person(final String firstName, final String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  public String getFullName() {
     return firstName + " " + lastName;

What do other classes see? Well, they will not see the private fields. To them this class is like a black box (they cannot see /affect its inner workings) that looks like this:

public class Person {
  public Person(final String firstName, final String lastName);
  public String getFullName();

If we change how it works without changing the public-facing functionality, we do not need to worry about the other classes.

Unit test
Q: How do we ensure that our class continues to provide the same functionality?
A: Unit tests.

Here is what the test for this class might look like:

import org.junit.Assert;
import org.junit.Test;

public class PersonTest {
	public void testHappyPath() {
		final Person p = new Person("Vincent", "Fleetwood");
		Assert.assertEquals("Vincent Fleetwood", p.getFullName());

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s