kafter2
kafter2

Reputation: 2253

What's meant by "Data Encapsulation"? Use private data fields or methods?

Say I have a ClassA and ClassB extends ClassA

ClassA {
    private int x;

    private void m1()
    {

    }
}

ClassB extends ClassA {

}

Under data encapsulation, we should private the data field and methods. Is that correct?

But, in this case, ClassB can not use ClassA's data field and methods.

So, under data encapsulation should I use private access modifiers only?

Can I use protected access modifier rather than private to solve the problem under the rule of data encapsulation?

Upvotes: 2

Views: 1811

Answers (2)

invalidsyntax
invalidsyntax

Reputation: 650

Essentially, encapsulation is a way of making sure certain functions in a class are only ran by processes that are tested and known to work. If a function has no reason to be called by any object other than the ones you intend it to, why should it be given the ability to be seen and accidentally called?

It's really more a form of programmer controls, setting up rules and basic guidelines of proper code use, especially in an API scenario where you only want to expose certain functions or classes.

"Good practice" states you should be using 'private' for functions that do not interface with anything other than the class itself. For functions that need to interface with children classes, you can use protected. For all other interfacing between other classes, use public.

Upvotes: 2

Ted Hopp
Ted Hopp

Reputation: 234857

There is no rule that all methods need to be private.

Data encapsulation usually refers to hiding the details of implementation from client classes. It usually does not involve hiding all methods, since those are the public (or, in some cases, inherited) contract between the class and the client classes (and/or subclasses) of that class. Private methods are used usually as helpers to the public methods, and are kept private because their function—perhaps their very existence is based on details of implementation.

Sometimes certain details of the implementation are published for use by subclasses. That is the principal use of protected methods. The implementation data may sometimes also be exposed in this way, but that is—how shall I put this?—frowned upon. Nevertheless, there is a tradeoff here between strict adherence to the ideal of encapsulation and the practicalities of programming.

Upvotes: 1

Related Questions