Code encapsulation in Java – class definitions inside methods

We can use encapsulation to hide some parts of application so that they can be visible only locally. Given code sample hides LogPersister and LogEntry class from other parts of application. Example code is given:

package rs.dodalovic.instance_field_initializer;

import java.util.Date;

public class EncapsulationDemo {
    public static void main(String[] args) {
        class LogEntry {
            private Date timestamp;
            private String content;
            private String threadID;

            public LogEntry(Date timestamp, String content, String threadID) {
                this.timestamp = timestamp;
                this.content = content;
                this.threadID = threadID;
            }
        }

        class LogPersister {
            public void persist(LogEntry logEntry) {
                System.out.println(logEntry);
            }
        }
        new LogPersister().persist(new LogEntry(new Date(), "Log content", "TD-23857"));
    }
}

Stay tuned and please – don’t forget to subscribe in case you’re eager to find out what’s coming next in upcoming posts.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s