programing tip

캡슐화 vs 추상화?

itbloger 2020. 6. 27. 11:45
반응형

캡슐화 vs 추상화?


다음은 캡슐화 및 추상화에 대한 간략한 정의입니다.

추출:

Java의 추상화 프로세스는 특정 세부 사항을 숨기고 오브젝트의 필수 기능 만 표시하는 데 사용됩니다. 즉, 객체 (인터페이스)의 외부 뷰를 처리합니다. 다른 사이트에서 이것을 볼 수있는 유일한 좋은 예는 인터페이스입니다.

캡슐화 :

기본적으로 private, public, protected 등과 같은 수정 자의 도움으로 객체 상태를 숨기는 것에 관한 것입니다. 필요한 경우에만 공개 메소드를 통해 상태를 노출합니다.

처럼 우리는 수정과 달성 무엇을 private, public또한 아무것도뿐만 아니라 추상화 개념없는 측면 세상 밖으로에서 불필요한 세부 사항을 숨 깁니다

위의 설명에서 캡슐화는 추상화의 일부이거나 추상화의 일부라고 말할 수 있습니다. 그렇다면 왜 캡슐화 용어가 추상화만을 다룰 수있을 때 발명 되었는가? 나는 그것들을 구별하는 큰 차이가있을 것이라고 확신하지만 그물에있는 대부분의 자료는 두 가지에 대해 거의 같은 것을 말합니다.

이 질문은이 포럼에서 이미 제기되었지만 구체적인 의심으로 다시 게시하고 있습니다. 일부 응답자들은 또한 추상화는 개념이고 캡슐화는 구현이라고 말합니다. 그러나 나는 이것을 사지 않습니다-그것이 사실이라면,이 두 가지 다른 개념이 우리를 혼란스럽게한다고 생각할 수 있습니다.

업데이트 : -5 년 후 나는이 게시물과 아래의 답변을 기반으로 요점 인 내 자신의 답변을 생각해 냈습니다.

  1. 추상화와 캡슐화의 차이?
  2. 캡슐화 vs 추상화 실제 예제

캡슐화 는 추상화의 일부로 사용되는 전략입니다. 캡슐화는 객체의 상태를 나타냅니다. 객체는 상태를 캡슐화하고 외부에서 숨 깁니다. 클래스의 외부 사용자는 메소드를 통해 클래스와 상호 작용하지만 클래스 상태에 직접 액세스 할 수는 없습니다. 따라서 클래스 는 상태와 관련된 구현 세부 사항을 추상화 합니다.

추상화 는보다 일반적인 용어이며, (다른 것들 중에서도) 서브 클래 싱으로도 달성 할 수 있습니다. 예를 들어, List표준 라이브러리 의 인터페이스 는 일련의 항목에 대한 추상화이며, 위치에 따라 색인이 생성되며, 구체적인 예 ListArrayList또는입니다 LinkedList. List사용중인 목록의 세부 사항에 대해 초록 과 상호 작용하는 코드입니다 .

캡슐화로 기본 상태를 숨기지 않고 추상화를 수행 할 수없는 경우가 종종 있습니다. 클래스가 내부 상태를 노출하면 내부 작업을 변경할 수 없으므로 추상화 할 수 없습니다.


추상화 는 중요한 용어에 초점을 맞추기 위해 더 간단한 용어로, 즉 세부 사항을 추상화하는 개념입니다 (예를 들어, 예술가가 색깔 또는 모양). 동일한 개념이 상속 계층 구조를 사용하여 OOP로 변환되며, 더 추상적 인 개념이 맨 위에 있고, 더 구체적인 개념이 맨 아래에 있으며, 추상 개념을 기반으로합니다. 가장 추상적 인 수준에는 구현 세부 사항이 전혀 없으며 아마도 공통성이 거의 없으며 추상화가 감소함에 따라 추가됩니다.

예를 들어, 맨 위에 단일 메소드가있는 인터페이스가있을 수 있고 다음 레벨은 몇 가지 추상 클래스를 제공합니다.이 클래스는 최상위 레벨에 대한 세부 사항을 채우거나 채우지 않을 수도 있지만 자체 추상 메소드를 추가하여 분기합니다. 그런 다음이 추상 클래스 각각에 대해 나머지 모든 메소드의 구현을 제공하는 구체적인 클래스입니다.

캡슐화기술 입니다. 추상화를 돕기위한 것일 수도 있고 아닐 수도 있지만, 확실히 정보 숨기기 및 / 또는 조직에 관한 것입니다. 그것은 데이터와 기능이 어떤 방식으로 그룹화 될 것을 요구합니다. 물론 좋은 OOP 관행은 추상화에 의해 그룹화되어야합니다. 그러나 유지 보수성 등을 돕는 다른 용도가 있습니다.


캡슐화는 추상화의 일부이거나 추상화의 하위 세트라고 말할 수 있습니다.

그것들은 다른 개념입니다.

  • 추상화는 객체의 불필요하거나 중요하지 않은 속성을 모두 제거하고 도메인에 가장 적합한 특성 만 유지하는 프로세스입니다.

    예 : 사람 : 이름과 성 및 SSN을 유지하기로 결정합니다. 나이, 신장, 체중 등은 관련이없는 것으로 무시됩니다.

    추상화는 디자인이 시작되는 곳입니다.

  • 캡슐화는 추상화 프로세스 중에 유지하도록 허용 된 속성에 적합한 작업을 인식하는 다음 단계입니다. 데이터와 데이터에 작용하는 작업을 연관시킵니다.
    즉 데이터와 메소드가 함께 번들로 제공됩니다.

캡슐화가 캡슐 또는 장치에 불필요한 데이터를 숨기고 있음

추상화는 객체의 필수 기능을 보여줍니다

캡슐화는 외부 클래스 및 인터페이스에서 멤버를 숨기는 데 사용됩니다. public, private, protected 등 c #.에서 제공되는 액세스 수정 자 사용 예 :

Class Learn
{
  private int a;         // by making it private we are hiding it from other
  private void show()   //class to access it
  {
   console.writeline(a);
  }
}

여기에 단위 또는 캡슐 즉 클래스로 랩 데이터가 있습니다.

추상화는 캡슐화의 반대입니다.

추상화는 중요한 관련 데이터를 사용자에게 보여주기 위해 사용됩니다. 가장 실제적인 예 휴대폰에서는 카메라, mp3 플레이어, 통화 기능, 녹음 기능, 멀티미디어 등과 같은 다양한 유형의 기능을 볼 수 있습니다. 내부 엔지니어링 대신 관련 정보 만 볼 수 있기 때문에 추상화입니다.

 abstract class MobilePhone
    {
        public void Calling();       //put necessary or essential data
        public void SendSMS();       //calling n sms are main in mobile
    }

    public class BlackBerry : MobilePhone   // inherited main feature
    {
        public void FMRadio();            //added new
        public void MP3();
        public void Camera();
        public void Recording();

    }

Abstraction is a very general term, and abstraction in software is not limited to object-oriented languages. A dictionary definition: "the act of considering something as a general quality or characteristic, apart from concrete realities, specific objects, or actual instances".

Assembly language can be thought of as an abstraction of machine code -- assembly expresses the essential details and structure of the machine code, but frees you from having to think about the opcodes used, the layout of the code in memory, making jumps go to the right address, etc.

Your operating system's API is an abstraction of the underlying machine. Your compiler provides a layer of abstraction which shields you from the details of assembly language. The TCP/IP stack built into your operating system abstracts away the details of transmitting bits over a network. If you go down all the way to the raw silicon, the people who designed your CPU did so using circuit diagrams written in terms of "diodes" and "transistors", which are abstractions of how electrons travel through semiconductor crystals.

In software, everything is an abstraction. We build programs which simulate or model some aspect of reality, but by necessity our models always abstract away some details of the "real thing". We build layer on layer on layer of abstractions, because it is the only way we get anything done. (Imagine you were trying to make, say, a sudoku solver, and you had to design it using only semiconductor crystals. "OK, I need a piece of N-type silicon here...")

In comparison, "encapsulation" is a very specific and limited term. Some of the other answers to this question have already given good definitions for it.


Answering my own question after 5 years as i feel it still need more details

Abstraction:

Technical Definition :- Abstraction is a concept to hide unnecessary details(complex or simple) and only show the essential features of the object. There is no implementaion here its just an concept

What it means practically:- When i say my company needs some medium/device so that employees can connect to customer . This is the purest form of abstaction(like interface in java) as that device/medium can be phone or internet or skype or in person or email etc. I am not going into nitty gritty of device/medium

Even when i say my company needs some medium/device so that employees can connect to customer through voice call. Then also i am talking abstract but at bit lower level as device/medium can be phone or skype or something else etc

Now when i say my company needs some phone so that employees can connect to customer through voice call. Then also i am talking abstract but at bit lower level as phone can be of any company like iphone or samsung or nokia etc

Encapsulation:- Its basically about hiding the state(information) of object with the help of modifiers like private,public,protected etc. we expose the state thru public methods only if require.

What it means practically:- Now when i say my company needs some iphone so that employees can connect to customer through voice call.Now i am talking about some concrete object(like iphone). Even though i am not going into nitty gritty of iphone here too but iphone has some state/concrecrete info/implementation associated with it where device/medium does not have. When i say concrete object, actually it means any object which has some(not complete like java abstract class) implementation/info associated with it.

So iphone actually used here encapsulation as strategy to hide its state/information and expose only the ones which it think should be exposed. So both abstraction and encapsulation hides some unnecessary details but abstraction at the concept level and encapsulation actually at implementation level

This is the gist based on answers in this post and below ones

  1. difference between abstraction and encapsulation?
  2. encapsulation vs abstraction real world example

Encapsulation - the process of hiding components of the class to prevent direct access from the outside. It is achieved by using "private" modifier to prevent direct access to some class members (data field or method) from other classes or objects meanwhile providing access to these private members by public members (Interface). That make the class members protected as human organs hidden/encapsulated under the skin or some shield.

Abstraction - A principle must be followed in writing OOP program that say "you must include in the class only components that are interesting in the task of the program". For example: the object student has a lot of characters as a human: name, age, weight, hair color, eye color, etc. But, when you create a class in OOP to work with students you should include only those characters that really matter for student database: name, age, specialty, level, marks ... etc. in C++ you can create abstract class by using the modifier "virtual" with any methods in the class and that will make it unusable in direct but you can derive other classes from it and create implementation for its members with adding required members based on the task.


This is how I understood it:

In Object oriented programming, we have something called classes. What are they for? They are to store some state and to store some methods to change that state i.e., they are encapsulating state and its methods.

It(class) does not care about the visibility of its own or of its contents. If we choose to hide the state or some methods, it is information hiding.

Now, take the scenario of an inheritance. We have a base class and a couple of derived (inherited) classes. So, what is the base class doing here? It is abstracting out some things from the derived classes.

All of them are different, right? But, we mix them up to write good object oriented programs. Hope it helps :)


Abstraction delineates a context-specific, simplified representation of something; it ignores contextually-irrelevant details and includes contextually-important details.

Encapsulation restricts outside access to something's parts and bundles that thing's state with the procedures that use the state.


Take people, for instance. In the context of surgery a useful abstraction ignores a person's religious beliefs and includes the person's body. Further, people encapsulate their memories with the thought processes that use those memories. An abstraction need not have encapsulation; for instance, a painting of a person neither hides its parts nor bundles procedures with its state. And, encapsulation need not have an associated abstraction; for instance, real people (not abstract ones) encapsulate their organs with their metabolism.


NOTE: I am sharing this. It is not mean that here is not good answer but because I easily understood.

Answer:

When a class is conceptualized, what are the properties we can have in it given the context. If we are designing a class Animal in the context of a zoo, it is important that we have an attribute as animalType to describe domestic or wild. This attribute may not make sense when we design the class in a different context.

Similarly, what are the behaviors we are going to have in the class? Abstraction is also applied here. What is necessary to have here and what will be an overdose? Then we cut off some information from the class. This process is applying abstraction.

When we ask for difference between encapsulation and abstraction, I would say, encapsulation uses abstraction as a concept. So then, is it only encapsulation. No, abstraction is even a concept applied as part of inheritance and polymorphism.

Go here for more explanation about this topic.


Lets try to understand in a different way.

What may happen if Abstraction is not there and What may happen if Encapsulation is not there.

If Abstraction is not there, then you can say the object is use less. You cannot identify the object nor can you access any functionality of it. Take a example of a TV, if you do not have an option to power on, change channel, increase or decrease volume etc., then what's the use of TV and how do you use it ?

If Encapsulation is not there or not being implemented properly, then you may misuse the object. There by data/components may get misused. Take the same example of TV, If there is no encapsulation done to the volume of TV, then the volume controller may be misused by making it come below or go beyond its limit (0-40/50).


Encapsulation protects to collapse the internal behaviour of object/instance from external entity. So, a control should be provided to confirm that the data which is being supplied is not going to harm the internal system of instance/object to survive its existance.

Good example, Divider is a class which has two instance variable dividend and divisor and a method getDividedValue.

Can you please think, if the divisor is set to 0 then internal system/behaviour (getDivided ) will break.

So, the object internal behaviour could be protected by throwing exception through a method.


in a simple sentence, I cay say: The essence of abstraction is to extract essential properties while omitting inessential details. But why should we omit inessential details? The key motivator is preventing the risk of change. You might consider abstraction is same as encapsulation. But encapsulation means the act of enclosing one or more items within a container, not hiding details. If you make the argument that "everything that was encapsulated was also hidden." This is obviously not true. For example, even though information may be encapsulated within record structures and arrays, this information is usually not hidden (unless hidden via some other mechanism).

참고URL : https://stackoverflow.com/questions/8960918/encapsulation-vs-abstraction

반응형