Nice programing

추상화와 캡슐화는 어떻게 다릅니 까?

nicepro 2020. 11. 12. 20:12
반응형

추상화와 캡슐화는 어떻게 다릅니 까?


인터뷰를 준비 중이며 OOP 개념을 정리하기로 결정했습니다. 사용 가능한 기사가 수백 개 있지만 각각 다르게 설명하는 것 같습니다. 일부 말한다

추상화는 "체계적인 변형이있는 공통 패턴을 식별하는 프로세스입니다. 추상화는 공통 패턴을 나타내며 사용할 변형을 지정하는 수단을 제공합니다"(Richard Gabriel).

추상 클래스를 통해 달성됩니다.

일부 다른 하나는 말한다

추상화는 객체의 클라이언트에게 필요한 세부 정보 만 표시하는 것을 의미합니다.

Employee 클래스에 "CalculateSalary"메서드가 있다고 가정 해 보겠습니다. EmployeeId를 매개 변수로 사용하고 이번 달 직원의 급여를 정수 값으로 반환합니다. 이제 누군가가 그 방법을 사용하고 싶다면. 그는 Employee 개체가 급여를 계산하는 방법에 대해 신경 쓸 필요가 없습니까? 그가 관심을 가질 필요가있는 유일한 것은 메소드의 이름, 입력 매개 변수 및 결과 멤버의 형식입니다.

나는 몇 번이고 봤는데 결과가 나에게 적절한 대답을주지 않는 것 같다. 자, 캡슐화가이 모든 것에 적합합니까? 검색 결과 스택 오버플로 질문을 찾았습니다 . 그 질문에도 답변을 혼동 한 다음 , 그것을 말한다

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

그리고 여기 또 다른 평판이 멤버는 말한다

그들은 다른 개념입니다.

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

이제 나는 전체 개념을 엉망으로 만들었습니다. 추상 클래스, 상속, 액세스 지정자 등에 대해 알고 있습니다. 인터뷰에서 추상화 및 / 또는 캡슐화에 대한 질문을받을 때 어떻게 대답해야하는지 알고 싶습니다 .

중복으로 표시하지 마십시오 . 비슷한 질문이 몇 가지 있다는 것을 알고 있습니다. 그러나 나는 상충되는 설명들 사이의 혼란을 피하고 싶다. 누구든지 신뢰할 수있는 링크를 제안 할 수 있습니까? 다시 혼동을 일으키지 않는 한 stackoverflow 질문에 대한 링크도 환영합니다. :)

편집 : 답변이 필요합니다, 약간의 C # 지향


추상화는 객체의 클라이언트에게 필요한 세부 정보 만 표시하는 것을 의미합니다.

사실 그것은 캡슐화입니다. 캡슐화와 데이터 숨김으로 인해 혼동되지 않도록 위키피디아 기사의 첫 부분을 참조하십시오. http://en.wikipedia.org/wiki/Encapsulation_ (객체 지향 _ 프로그래밍)

단순히 속성 뒤에 모든 클래스 멤버를 1 : 1로 숨기는 것은 전혀 캡슐화되지 않습니다. 캡슐화는 불변성을 보호하고 구현 세부 사항을 숨기는 것입니다.

여기에 대한 좋은 기사가 있습니다. http://blog.ploeh.dk/2012/11/27/Encapsulationofproperties/ 또한 해당 기사에 링크 된 기사를 살펴보십시오.

클래스, 속성 및 액세스 한정자는 C #에서 캡슐화를 제공하는 도구입니다.

복잡성을 줄이기 위해 캡슐화를 수행합니다.

추상화는 "체계적인 변형이있는 공통 패턴을 식별하는 프로세스입니다. 추상화는 공통 패턴을 나타내며 사용할 변형을 지정하는 수단을 제공합니다"(Richard Gabriel).

예, 그것은 추상화에 대한 좋은 정의입니다.

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

예, 그들은 다른 개념입니다. 추상화는 실제로 귀하의 도메인에만 적합한 객체를 만드는 것과 반대임을 명심하십시오. 객체를 일반적으로 도메인에 적합하게 만들기 위해서입니다!

실제 문제가 있고 특정 솔루션을 제공하는 경우 추상화를 사용하여 동일한 공통 패턴을 가진 더 많은 문제를 해결할 수도있는보다 일반적인 솔루션을 공식화 할 수 있습니다. 그런 식으로 구성 요소의 재사용 가능성을 높이거나 동일한 도메인 또는 다른 도메인에 대해 만든 다른 프로그래머가 만든 구성 요소를 사용할 수 있습니다.

좋은 예는 .net 프레임 워크에서 제공하는 클래스 (예 : 목록 또는 컬렉션)입니다. 이들은 거의 모든 곳에서 그리고 많은 도메인에서 사용할 수있는 매우 추상적 인 클래스입니다. .net이 EmployeeList 클래스와 특정 속성을 가진 직원 및 회사 목록 만 포함 할 수있는 CompanyList 만 구현했다고 상상해보십시오. 이러한 클래스는 많은 경우에 쓸모가 없습니다. 예를 들어 CarList의 전체 기능을 다시 구현해야한다면 얼마나 고통 스러울까요? 따라서 "목록"은 Employee, Company 및 Car에서 제외됩니다. 목록 자체는 자체 클래스에서 구현할 수있는 추상 개념입니다.

인터페이스, 추상 클래스 또는 상속 및 다형성은 C #에서 추상화를 제공하는 도구입니다.

재사용 성을 제공하기 위해 추상화를 수행합니다.


캡슐화 : getter 및 setter 등을 사용하여 데이터 숨기기

추상화 : 추상 클래스 및 인터페이스 등을 사용하여 구현 숨기기


추상화 및 캡슐화 예 이미지 소스

추상화 : 고양이의 왼쪽 상단과 오른쪽 상단 이미지로 윤곽이 그려집니다. 외과 의사와 노파는 동물을 다르게 디자인 (또는 시각화)했습니다. 같은 방식으로 애플리케이션의 필요에 따라 Cat 클래스에 다른 기능을 배치합니다. 모든 고양이에는 간, 방광, 심장 및 폐가 있지만 고양이가 '자르고'만 필요하다면 애플리케이션의 고양이를 오른쪽 상단이 아닌 왼쪽 상단의 디자인으로 추상화합니다.

캡슐화 : 테이블 위에 서있는 고양이에 의해 윤곽이 그려집니다. 그것이 고양이 외부의 모든 사람들이 고양이를 . 고양이의 실제 구현이 왼쪽 상단인지 오른쪽 상단인지 또는 둘 다의 조합인지 걱정할 필요가 없습니다.


PS : 전체 이야기를 들으려면 동일한 질문에 대해 여기이동 하십시오 .


Encapsulation과 Abstraction을 간단한 방법으로 시연 해 보겠습니다.

  • 데이터와 함수를 단일 단위 (클래스라고 함)로 래핑하는 것을 캡슐화라고합니다. 내부 데이터 구조 및 코드와 같은 개체에 대한 정보를 포함하고 숨기는 캡슐화입니다.

캡슐화는-

  • 복잡성 숨기기,
  • 데이터와 기능을 함께 결합,
  • 복잡한 방법의 비공개 만들기,
  • 인스턴스 변수를 비공개로 만들기,
  • 최종 사용자로부터 불필요한 데이터 및 기능 숨기기.

캡슐화는 추상화를 구현합니다.

그리고 추상화는-

  • 필요한 것을 보여주기,
  • 데이터는 최종 사용자로부터 추상화해야합니다.

예를 보자-

아래 이미지는 "데이터베이스에 추가 할 고객 세부 정보"GUI를 보여줍니다.

고객 화면 GUI

이미지를 보면 고객 클래스가 필요하다고 말할 수 있습니다.

1 단계 : 고객 클래스에 필요한 것은 무엇입니까?

  • 고객 코드 및 고객 이름을 저장하는 2 개의 변수.

  • 1 데이터베이스에 고객 코드 및 고객 이름을 추가하는 기능.

  namespace CustomerContent
    {
       public class Customer
       {
           public string CustomerCode = "";
           public string CustomerName = "";
           public void ADD()
           {
              //my DB code will go here
           }

이제 ADD 방법 만 여기서 만 작동하지 않습니다.

2 단계 : 유효성 검사는 어떻게 작동하고 ADD 함수는 작동합니까?

데이터베이스 연결 코드와 유효성 검사 코드 (추가 방법)가 필요합니다.

     public bool Validate()
     {
    //Granular Customer Code and Name
    return true;
     }

     public bool CreateDBObject()
     {
    //DB Connection Code
    return true;
     }


class Program
{
   static void main(String[] args)
   {
     CustomerComponent.Customer obj = new CustomerComponent.Customer;

     obj.CustomerCode = "s001";
     obj.CustomerName = "Mac";

     obj.Validate();
     obj.CreateDBObject();

     obj.ADD();
    }
}

이제 최종 사용자에게 추가 방법 ( Validate(); CreateDBObject()[복잡하고 추가 방법])을 보여줄 필요가 없습니다. 최종 사용자는 레코드를 추가 할 고객 코드, 고객 이름 및 추가 버튼 만보고 알면됩니다. 최종 사용자 데이터베이스에 데이터를 추가하는 방법에 대해 신경 쓰지 않습니까?.

단계 -3 : 최종 사용자의 상호 작용을 포함하지 않는 추가적이고 복잡한 방법을 비공개합니다.

따라서 Complicated 및 Extra 메서드를 Private 대신 Public (즉, 해당 메서드 숨기기)으로 만들고 obj.Validate(); obj.CreateDBObject();Program 클래스에서 main을 삭제하여 Encapsulation을 수행합니다.

즉, 최종 사용자에 대한 인터페이스를 단순화하는 것은 캡슐화입니다.

이제 전체 코드는 다음과 같습니다.

 namespace CustomerContent
 {
     public class Customer
     {
        public string CustomerCode = "";
        public string CustomerName = "";

        public void ADD()
        {
           //my DB code will go here
        }

        private bool Validate()
        {
           //Granular Customer Code and Name
           return true;
        }

        private bool CreateDBObject()
        {
           //DB Connection Code
           return true;
        }


  class Program
  {
     static void main(String[] args)
     {
        CustomerComponent.Customer obj = new CustomerComponent.Customer;

        obj.CustomerCode = "s001";

        obj.CustomerName = "Mac";

        obj.ADD();
   }
}

요약 :

1 단계 : 고객 클래스에 필요한 것은 무엇입니까? 이다 추상화 .

Step -3: Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction is Encapsulation.

P.S. - The code above is hard and fast.

UPDATE: There is an video on this link to explain the sample: What is the difference between Abstraction and Encapsulation


I think they are slightly different concepts, but often they are applied together. Encapsulation is a technique for hiding implementation details from the caller, whereas abstraction is more a design philosophy involving creating objects that are analogous to familiar objects/processes, to aid understanding. Encapsulation is just one of many techniques that can be used to create an abstraction.

For example, take "windows". They are not really windows in the traditional sense, they are just graphical squares on the screen. But it's useful to think of them as windows. That's an abstraction.

If the "windows API" hides the details of how the text or graphics is physically rendered within the boundaries of a window, that's encapsulation.


Object-Oriented Analysis and Design (OOAD) is actually based on four principles. They are:

  • Abstraction: means that you only incorporate those features of an entity which are required in your design. So, if every bank account has an opening date but your application doesn't need to know an account's opening date, then you simply don't add the OpeningDate field in your Object-Oriented Design of the BankAccount class. Abstraction in OOAD has nothing to do with abstract classes in programming. By this principle, your entities are a abstraction of what they actually are. You design an abstraction of Bank Account down to only that level of detail that your application's needs.

  • Inheritance: is more like a trick than an actual principle, which saves you from re-writing those functionalities that you have written somewhere else. The only thing is that there has to be a relation between the new code you are writing and the old code you are wanting to re-use. Just like you may inherit your parents' wealth, you may inherit fields and methods from your parent class. So, taking everything that parent class has and then adding something more if need be, is inheritance. Don't go looking for inheritance in your Object Oriented Design. Inheritance will present itself.

  • Polymorphism: is a consequence of inheritance. Inheriting a method from the parent is useful, but being able to modify a method if the situation demands, is polymorphism. You may implement a method in the subclass with exactly the same signature as in parent class so that when called, the method from child class is executed. This is the polymorphism.

  • Encapsulation: means bundling the related functionality together and giving access to only the needful. This principle is the basis of designing classes in Object Oriented Design where:

    • you put related data and methods together; and,
    • not all the pieces of data and methods may be public.

Another simplified answer is here.


People who argue that "Abstraction of OOAD results in the abstract keyword of OOP"... Well that is simply not correct.

Example: When you design a University in an application using object oriented principles, you only design an "abstraction" of the university. Even though there is usually one cash dispensing ATM in almost every university, you may not incorporate that fact if it's not needed for your application. And now though you have designed only an abstraction of the university, you are not required to put abstract in your class declaration. Your abstract design of university will be a normal class in your application.


my 2c

the purpose of encapsulation is to hide implementation details from the user of your class e.g. if you internally keep a std::list of items in your class and then decide that a std::vector would be more effective you can change this without the user caring. That said, the way you interact with the either stl container is thanks to abstraction, both the list and the vector can for instance be traversed in the same way using similar methods (iterators).


One example has always been brought up to me in the context of abstraction; the automatic vs. manual transmission on cars. The manual transmission hides some of the workings of changing gears, but you still have to clutch and shift as a driver. Automatic transmission encapsulates all the details of changing gears, i.e. hides it from you, and it is therefore a higher abstraction of the process of changing gears.


Encapsulation: Hiding implementation details (NOTE: data AND/OR methods) such that only what is sensibly readable/writable/usable by externals is accessible to them, everything else is "untouchable" directly.

Abstraction: This sometimes refers specifically to a type that cannot be instantiated and which provides a template for other types that can be, usually via subclassing. More generally "abstraction" refers to making/having something that is less detailed, less specific, less granular.

There is some similarity, overlap between the concepts but the best way to remember it is like this: Encapsulation is more about hiding the details, whereas abstraction is more about generalizing the details.


Abstraction and Encapsulation are confusing terms and dependent on each other. Let's take it by an example:

public class Person
    {
        private int Id { get; set; }
        private string Name { get; set; }
        private string CustomName()
        {
            return "Name:- " + Name + " and Id is:- " + Id;
        }
    }

When you created Person class, you did encapsulation by writing properties and functions together(Id, Name, CustomName). You perform abstraction when you expose this class to client as

Person p = new Person();
p.CustomName();

Your client doesn't know anything about Id and Name in this function. Now if, your client wants to know the last name as well without disturbing the function call. You do encapsulation by adding one more property into Person class like this.

public class Person
        {
            private int Id { get; set; }
            private string Name { get; set; }
            private string LastName {get; set;}
            public string CustomName()
            {
                return "Name:- " + Name + " and Id is:- " + Id + "last name:- " + LastName;
            }
        }

Look, even after addding an extra property in class, your client doesn't know what you did to your code. This is where you did abstraction.


As I knowit, encapsulation is hiding data of classes in themselves, and only making it accessible via setters / getters, if they must be accessed from the outer world.

Abstraction is the class design for itself.

Means, how You create Your class tree, which methods are general ones, which are inherited, which can be overridden,which attributes are only on private level, or on protected, how Do You build up Your class inheritance tree, Do You use final classes, abtract classes, interface-implementation.

Abstraction is more placed the oo-design phase, while encapsulation also enrolls into developmnent-phase.


I think of it this way, encapsulation is hiding the way something gets done. This can be one or many actions.

Abstraction is related to "why" I am encapsulating it the first place.

I am basically telling the client "You don't need to know much about how I process the payment and calculate shipping, etc. I just want you to tell me you want to 'Checkout' and I will take care of the details for you."

This way I have encapsulated the details by generalizing (abstracting) into the Checkout request.

I really think that abstracting and encapsulation go together.


Abstraction

In Java, abstraction means hiding the information to the real world. It establishes the contract between the party to tell about “what should we do to make use of the service”.

Example, In API development, only abstracted information of the service has been revealed to the world rather the actual implementation. Interface in java can help achieve this concept very well.

Interface provides contract between the parties, example, producer and consumer. Producer produces the goods without letting know the consumer how the product is being made. But, through interface, Producer let all consumer know what product can buy. With the help of abstraction, producer can markets the product to their consumers.

Encapsulation:

Encapsulation is one level down of abstraction. Same product company try shielding information from each other production group. Example, if a company produce wine and chocolate, encapsulation helps shielding information how each product Is being made from each other.

  1. If I have individual package one for wine and another one for chocolate, and if all the classes are declared in the package as default access modifier, we are giving package level encapsulation for all classes.
  2. 패키지 내에서 파일 된 각 클래스 (멤버 필드)를 개인으로 선언하고 해당 필드에 액세스 할 수있는 공용 메서드를 갖는 경우 이러한 방법으로 해당 필드에 클래스 수준 캡슐화를 제공합니다.

참고 URL : https://stackoverflow.com/questions/16938667/how-abstraction-and-encapsulation-differ

반응형