Abstraction in Java?

前端 未结 10 1829
鱼传尺愫
鱼传尺愫 2021-02-15 00:43

Today i heard from my friend, that encapsulation is not only achieving information hiding but also abstraction. How does it achieve?

public class employee {

           


        
10条回答
  •  迷失自我
    2021-02-15 01:11

    @ John your friend is right by implementing the encapsulation you also achieve abstraction.

    public class employee {
           private String name;
           private int id;   
           public void setName(String name){ 
             name= name+"something that you want to edit";
             this.name = name;      }   
           public String getName(){  
            return name;      }
       } 
    

    in this way you have edited ur set method and hided the details from the user which is nothing but abstraction... thus by writting getters and setters you hide user to do the unneccessary task...

    public void setName(String name){ 
             /*some internal logic suppose in database you want name 
             *should be added with its id but what user to do with it.*/
             this.name = name;      }   
           public String getName(){  
            /* now suppose you have recieved the name from
            *data base it has id but you want user to know only 
            name then you will write the logic here to show the name.*/
            return name;      }
    

    I know adding id to name is a stupid example but thats what i can think of right now... but consider for a very big project you many times write code in set(or call other method which modifies the parameters of it) then what... suppose you get the name but you want to save it in a encrypted form in db, then what. User dont care about the encryption but yes you have to... because its uneccesary to the user but important to you. So that should be in the code of yours but hidden from the user and thats what is all about abstraction*("HIDING THE UNNECCESARY DETAILS FROM USER")*

    EDITED:-Go to the source! Grady Booch says (in Object Oriented Analysis and Design, page 49, second edition):

    "Abstraction and encapsulation are complementary concepts: abstraction focuses on the observable behavior of an object... encapsulation focuses upon the implementation that gives rise to this behavior... encapsulation is most often achieved through information hiding, which is the process of hiding all of the secrets of object that do not contribute to its essential characteristics."

    from above you can conclude the same

提交回复
热议问题