Confused with Java Encapsulation Concept

后端 未结 6 1602
抹茶落季
抹茶落季 2021-01-03 06:37

Good day!

I am reading a Java book about encapsulation and it mentioned the getter and setter method.

I\'ve read that to hide the attributes, I must mark my

6条回答
  •  孤城傲影
    2021-01-03 07:22

    Yes and no. The point of encapsulation is that it prevents other classes from needing to know what your class is doing behind the scenes. If you store your name in a String (as you've done here), read/write it from a file, or do something different, the point of encapsulation is that to the user of your class it doesn't matter because all they see is String getName( ) and void setName (String name).

    Since the modification of the data is entirely under the control of your class here, it doesn't break encapsulation. If you did store name to file, then you could potentially do so in getAllInfo without any other user of the class being any the wiser. Since the observable behaviour from the outside of the class still hides what the internals of the class is doing, it's still encapsulated.

    That said, this is a very unconventional approach. Like I describe in the first paragraph, use of accessor methods (getters and setters) is a more idiomatic approach, and easier to understand for someone else using your code. You can do what you do, it doesn't break encapsulation, but it's not what I'd call elegant or typical.

提交回复
热议问题