What are the different types of encapsulation?

2020-06-04 09:35发布

What are the different types of encapsulation?

Am I right in thinking this basically refers to central OO concepts such as Abstraction, Polymorphism and Inheritance?

My understanding of encapsulation is that it is a method of hiding data / functionality, but I never really considered Polymorphism or Inheritance a form of encapsulation, although I can see how polymorphism could be considered encapsulation as it can hide the exact type of the object you are interacting with.

So, would you say that's about it, or am I missing some core concepts?

edit I just noticed in the comments someone mentioned it could refer to private / public methods, perhaps I'm thinking in to the question too much and expecting a more complicated answer than it really is?

7条回答
We Are One
2楼-- · 2020-06-04 10:23

"Candidate Definitions for Encapsulation:

  • Physically grouping together related operations or things.
  • GateKeeper of state or data.
  • Hiding implementation."

Sourced from: Encapsulation Definition

There are two parts/ways to achieve Encapsulation:

  • First, encapsulation is a technique that packages related data and behaviors into a single unit, i.e, Physical grouping of operations(behaviors)

E.g.:-

class Person {
    String name;
    int age;

    void talk() {
    }

    void think() {
    }

    void work() {
    }

    void play() {
    }
}
  • Second, encapsulation is a technique for protecting data from misuse by the outside world, which is referred as ‘information hiding’ or ‘data hiding’.

E.g.:-

class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public String getAge() {
        return age;
    }
}

Sourced from: What is Encapsulation in Java - the WHAT, WHY and HOW, spoiler author cites Interface as an example, which is not true. Interface are for Abstraction

查看更多
登录 后发表回答