Question

I am new to OOP and I have some doubts regarding encapsulation.

  1. What is mean by difference between "partial" and "weak" encapsulation? An example in java will help me.

  2. Does encapsulation means only place data in capsule like a class, or does an access modifier have to be there?

I read that encapsulation means to hide and club together data.

In this example:

class A{ 
  public int a;
  public void foo(){}
}

Is above code is example of encapsulation? If yes, then there is nothing hidden from outer world as a and foo are public. Must a and foo be private for this example to be considered encapsulation?

Was it helpful?

Solution

Here is a good explanation https://mail.mozilla.org/pipermail/es-discuss/2010-December/012334.html

Basically if you were implementing a java library or API you would aim for strong encapsulation, so that users couldn't access things they aren't supposed to.

Strong encapsulation means that no one can access secret internal variables because you have a proper inheritance heirachy and all that stuff is hidden.

Your example is very weak encapsulation because the variable a is public. If your class was an API and a was actually credit_card_details you would be in big trouble.

For starters you would set those variables as private and use getters and setters to access them.

Overall though, you need something abstracted in order to encapsulate it. The only other thing I have heard encapsulation refer to from an OOP perspective is simply bundling real world objects into classes

OTHER TIPS

Object orientation is about messages. If you can only ask for setting or getting a value inside an object, then the values are encapsulated. The only way to access them is via the predefined protocol, which is the setter or the getter or whatever other methods. If you have a public field, it looks like there's no encapsulation, but you still don't own the variable, think of it as a default set or get.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top