Ask the Expert

What is encapsulation in Java?

What is encapsulation in Java?

    Requires Free Membership to View

Java encapsulation is a programming concept that a language should support in order to object's state from its behavior. This is typically facilitated by means of hiding an object's data representing its state from modification by external components. Java offers four different "scope" realms--public, protected, private, and package--that can be used to selectively hide data constructs. The following example illustrates these:

package com.jeffhanson.test; // The public scope identifier makes this class available // to all external components public class MyClass { // The following field does not have a scope identifier // so it is "package" scope by default. This means that // only objects in the same package can access it. int aPackageScopedInt; // The following field has a "private" scope identifier. // This means that it can only be accessed by this class. int aPrivateScopedInt; // The following method has a "protected" scope identifier. // This means that it can only be accessed by this class, // classes that extend this class, and other classes in // the same package. protected int aProtectedMethod() { return 0; } }

This was first published in April 2003

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: