Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you explain this thing about encapsulation?

In response to What is your longest-held programming assumption that turned out to be incorrect? question, one of the wrong assumptions was:

That private member variables were private to the instance and not the class.

(Link)

I couldn't catch what he's talking about, can anyone explain what is the wrong/right about that with an example?

like image 528
Moayad Mardini Avatar asked Aug 31 '09 13:08

Moayad Mardini


People also ask

How do you explain encapsulation?

Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Another way to think about encapsulation is, that it is a protective shield that prevents the data from being accessed by the code outside this shield.

How do you explain encapsulation in Java?

Encapsulation in Java is the process by which data (variables) and the code that acts upon them (methods) are integrated as a single unit. By encapsulating a class's variables, other classes cannot access them, and only the methods of the class can access them.

Which can describe encapsulation best?

Which among the following best describes encapsulation? Explanation: It is a way of combining both data members and member functions, which operate on those data members, into a single unit.

What is the main reason for encapsulation?

Encapsulation is used to hide the values or state of a structured data object inside a class, preventing direct access to them by clients in a way that could expose hidden implementation details or violate state invariance maintained by the methods.


1 Answers

public class Example {
  private int a;

  public int getOtherA(Example other) {
    return other.a;
  }
}

Like this. As you can see private doesn't protect the instance member from being accessed by another instance.

BTW, this is not all bad as long as you are a bit careful. If private wouldn't work like in the above example, it would be cumbersome to write equals() and other such methods.

like image 105
Gregory Mostizky Avatar answered Sep 21 '22 08:09

Gregory Mostizky