This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
A public class can be accessed by everything. But what about the public methods in default classes? Is there a special purpose of public modifier for methods in default class?
Got this doubt because i noticed that main method will not work without public keyword even if in default class.
Public methods in non-public classes are quite common. They're used when we want to provide an implementation of public methods, but not make the implementing class available to the world.
For example, java.util.AbstractList defines a private class Itr implements Iterator, which is what we get when we call the iterator() method on ArrayList or LinkedList. The outside world can't reference this class, and doesn't need to know anything about it, other than that there's something there that implements Iterator.
Another example is if you define a non-public class and override toString() in that class. When you call System.out.println(instance_of_my_non_public_class), that ultimately leads to your non-public class's public toString() method getting called. The caller doesn't know anything about your class, other than that it extends Object and therefore has a public toString().
midhuna peru wrote:A public class can be accessed by everything. But what about the public methods in default classes? Is there a special purpose of public modifier for methods in default class?...
The fact is that public methods are always visible; the problem is that if you can't see the class, it's often difficult to call anything. However, as was pointed out to me recently, all objects are Objects, so you can always call its methods, and if they're overridden, the correct runtime method will be run even if the type itself is not visible.
Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
midhuna peru wrote:Can i get an example of how to access public method of non public class. A small code.
I already gave you two examples:
1. Any time you call iterator() on an ArrayList or LinkedList (probably other collections as well), you're getting a private class that implements Iterator, and you can call its public methods (hasNext(), next(), toString(), hashCode(), etc.).
2. Create a non-public class that extends Object--in other words, any non-public class at all. Write a public method that's declared to return Object, and returns an instance of this class. Pass that object to System.out.println(), or even just call its toString(), hashCode(), etc. methods directly.