posted 21 years ago
Hi Ravi,
Welcome to JavaRanch.
An example of Default access is easy: it is package level access. Consider making a database program where you have the actual database, a server program and a client program. You might create several packages to hold the classes that perform these functions, such as:
Now in the "database" package, I have 3 classes: file reader/writer; record manager; and lock manager. These do distinct jobs - the file reader is only concerned about putting data into the file in the right spot and getting it out again. The record manager is concerned with the concept of a record (breaking it into fields, allowing creates, reads, updates, and deletes). The lock manager is only concerned with locking and unlocking logical records.
I only want other classes to use the record manager to do all their work - it will call the lock manager and the file reader / writer when necessary. It could be potentially disasterous if some other class called my file reader / writer and overwrote some of my data without having been able to verify that the record was locked properly and the data was correct.
So therefore I want to make sure that any class in the database package can see my locking functions, but classes in other packages cant. Simple solution: default access!
-----
An example for protected access is a bit harder.
One not very useful example is debugging code. You have written a class that works, but in the process of building it you had to create some "interesting" debugging routines (similar to "toString()" methods). You do not want these to be available to the normal user of your class, but you think it would be very useful to anyone who extends your class. You cannot make it default access otherwise the extending code would also need to be in the same package. You cannot make it public or it would become available to every programmer and they probably dont want to be bothered with yet another method that they could but never will call. So that leaves protected as the best choice.
Take a look at JButton.paramString() for an example of this usage.
Another example is the Properties class - it has a "defaults" field which is protected - classes using Properties are not even aware that the defaults exist, but a class extending Properties would be able to access it.
Regards, Andrew