1

I have seen this question and I understand what theoretically the difference between public and private means. My understanding is as follows:

public means that it's "visible" / "accessible" everywhere. As in every class can see it. private is only "visible" / "accessible" in its declared class.

My first question is:

What does "visible" exactly mean? I'm not quite sure how to interpret the meaning of "this class can't "see" this method".

Second question is:

What is the functionality/use of these? In the second asnwer of the question, he explains that if we "encapsulate" our code, then we will make it "easier for ourselves to change the code later and not break anybody's else's code". What does this exactly mean?

Examples would help a lot

Slim Shady
  • 220
  • 3
  • 18
  • 1
    Please refer this : http://cs.gordon.edu/courses/cs112/kjrComplete/ch3/visibility.html not only this you can go through any java beginner tutorials, you will be able to get a good idea about the basics – Brooklyn99 Feb 07 '20 at 16:31

1 Answers1

2

With respect to the first question: What does "visible" exactly mean?

visibility translates to accessibility when talking of classes, whenever a class is declared public, that class is accessible to all the other classes of the project, and all the classes can access them as they like either by inheriting the class or instantiating a new object of the class. Similar concepts also transcend to public class members. However, one important point is that public class members such as methods and variables will only be visible/accessible to other classes if the containing class is not marked as private.

On the other hand, when the class is marked as private, it is hidden from all the classes in the codebase, you can think that the rest of the code won't even know that, that class exists.

Members of a private class are only accessible within the class and are hidden from the outside world. A private member will remain inaccessible for the outside world even if its class is marked as public.

Now, for the second question: What is the functionality/use of these?

Access modifiers are especially useful when you want to restrict as to what part of your class should be accessible from outside and what part should not be accessible.

For example, in general, it is a good idea to make class variables as private and then expose functions that will allow you to fetch those variables, the major benefit you get with this approach is that at any point of time in future, you can change how those variables are calculated and the changes would propagate to all the classes without having the need to change them, had the classes directly accessed the variable, it would have been very difficult to make the change without impacting other classes. This is just one example demonstrating how useful access modifiers can prove to be even for the simplest of things.

Hope this gives you a brief idea.

Shivam Mohan
  • 397
  • 3
  • 14