• Post Reply Bookmark Topic Watch Topic
  • New Topic

Access Modifiers  RSS feed

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Guys,

Im quite new in java.. I have knowledge in Access Modifiers, but I really can't understand why we need this? I mean, what is the relevance? Im thinking that we can put all as public.. Can someone explain to me why we need this?

Regards
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It has to do with object oriented programming principles. One important principle is encapsulation. If everything in your program was public, then any part of the program could change any data in any object. If you have a large program, and you'd want to know where a certain member variable is changed, then it would be really hard to find out where the change happens if the member variable were public - it could be anywhere in the program. When all member variables would be public, the program would quickly become a hard to understand mess.

To make the program easier to understand and easier to maintain, you want to make the different modules or classes as independent of each other as possible; the principle of loose coupling. One of the ways you can achieve this is by making classes hide their data as much as possible, by making the member variables private.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!