Home > Back-end >  Can we say a class with all public member variables and all public methods as encapsulated class?
Can we say a class with all public member variables and all public methods as encapsulated class?

Time:12-12

By definition, encapsulation in Java is a process of wrapping code and data together into a single unit. But if a class has 2 member variables and a method and both the variables and method has public access modifier, can we say that class as encapsulated class?

For example, can we say below class is encapsulated or not

public class AddNumbers {

     public int a;
     public int b;

     public void add(){
          System.out.println(a b);
     }
}

CodePudding user response:

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users

to make your class encapsulated you need

  • Declare class variables/attributes as private
  • provide public get and set methods to access and update the value of a private variable

your class has public data, that is, it is not protected (encapsulated) and therefore can be accessed and modified by everyone I recommend this reading for a better understanding of encapsulation

java_encapsulation

CodePudding user response:

Yes, or no. Depending on how one defines "encapsulation".

Given the phrasing of your question, I assume you are working with the definition of encapsulation from Wikipedia, which (as of now) reads

In object-oriented programming (OOP), encapsulation refers to the bundling of data with the methods that operate on those data, or the restricting of direct access to some of an object's components.

I disagree with this definition. Or more precisely, I think it unnecessarily distinguishes "encapsulation" and "data hiding" which is not in line with how I see the term "encapsulation" used in day-to-day conversations. In fact even the Wikipedia talk page mentions this problem of the definition (with no apparent counter-voices).

So if you follow that Wikipedia definition, then yes, your code uses encapsulation ("an encapsulated class" is not a phrase I've ever heard anyone use this way, I'd avoid it).

If you follow the school of thought that information hiding and encapsulation are synonymous (or at least very tightly bound together) then your code is not using encapsulation.

See this paragraph from the Wikipedia article on Information Hiding:

The term encapsulation is often used interchangeably with information hiding. Not all agree on the distinctions between the two, though; one may think of information hiding as being the principle and encapsulation being the technique.

  • Related