Simple way to understand Encapsulation and Abstraction

后端 未结 15 1128
谎友^
谎友^ 2020-11-27 09:47

Learning OOP concepts especially interested to understand Abstraction and Encapsulation in depth.

Checked out the below already

Abstraction VS Information Hi

相关标签:
15条回答
  • 2020-11-27 10:49
    public abstract class Draw {
        public abstract void drawShape(); // this is abstraction.  Implementation detail need not to be known.
        // so we are providing only necessary detail by giving drawShape(); No implementation. Subclass will give detail.
    
    
        private int type;    // this variable cannot be set outside of the class. Because it is private.
        // Binding private instance variable with public setter/getter method is encapsulation 
    
        public int getType() { 
            return type;
        }
    
        public void setType(int type) {  // this is encapsulation. Protecting any value to be set.
            if (type >= 0 && type <= 3) {
                this.type = type;
            } else {
                System.out.println("We have four types only. Enter value between 0 to 4");
                try {
                    throw new MyInvalidValueSetException();
                } catch (MyInvalidValueSetException e) {
                    e.printStackTrace();
                }
    
            }
        }
    }
    

    Abstraction is related with methods where implementation detail is not known which is a kind of implementation hiding.
    Encapsulation is related with instance variable binding with method, a kind of data hiding.

    0 讨论(0)
  • 2020-11-27 10:52

    Abstraction is hiding the information or providing only necessary details to the client.

    e.g Car Brakes- You just know that pressing the pedals will stop the vehicle but you don't need to know how it works internally.

    Advantage of Abstraction Tomorrow if brake implementation changes from drum brake to disk brake, as a client, you don't need to change(i.e your code will not change)

    Encapsulation is binding the data and behaviors together in a single unit. Also it is a language mechanism for restricting access to some components(this can be achieved by access modifiers like private,protected etc.)

    For e.g. Class has attributes(i.e data) and behaviors (i.e methods that operate on that data)

    0 讨论(0)
  • 2020-11-27 10:52

    Abstraction is the process where you "throw-away" unnecessary details from an entity you plan to capture/represent in your design and keep only the properties of the entity that are relevant to your domain.
    Example: to represent car you would keep e.g. the model and price, current location and current speed and ignore color and number of seats etc.

    Encapsulation is the "binding" of the properties and the operations that manipulate them in a single unit of abstraction (namely a class).
    So the car would have accelarate stop that manipulate location and current speed etc.

    0 讨论(0)
提交回复
热议问题