We can restrict others to create objects of our classes by defining constructors as private, we can restrict. Even though, we can write some special kind of methods to get object of our classes. Those methods must be static.
This is similar to
In
This is similar to
java.lang.Runtime class. You will not create object to that class, since java.lang.Runtime class's constructor has private access. So, you will not create object to that class. But you can get object of that class with the help of getRuntime() static method of the same class. By doing this, we can restrict others to read(monitor) or write(change) our resources. This is exactly happening with java.lang.System class.In
System class most of the member are static only (out, in, err, etc). You will not get object of System class, but you can use getProperty(String str), gc(), exit(int) etc methods of that class. Since all are static methods.Here i am giving one example of that.
public class Product {
private Product() {
System.out.println("Hi, i am new object of Product class.");
}/*Product()*/
public static Product getProduct() {
System.out.println("Hi, i am getProduct() method.");
System.out.println("I will create Product class object.");
return new Product();
}/*getProduct()*/
public String getDirectory() {
return System.getProperty("user.dir");
}/*getTime()*/
}/*Product*/
class Test {
public static void main(String[] args) {
System.out.println("Hi, i am main() method.");
Product p = Product.getProduct();
System.out.println("Current Directory : " + p.getDirectory());
}/*main()*/
}/*Test*/
Excellent srikanth....but i forgot fundamentals already hehe....
ReplyDeleteI Really appreciate u for sharing this wonderful concept for us
ReplyDeletereally very nice srikanth... nice concept.. helpful for interveiws.
ReplyDeleteGood Kantharao, There were few more classes of same kind in java.sql package
ReplyDelete