aspose file tools*
The moose likes Beginning Java and the fly likes Java constructore Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java constructore" Watch "Java constructore" New topic
Author

Java constructore

Adi Sharma
Ranch Hand

Joined: May 18, 2009
Posts: 33
Hi,
I got the following and could not make any sense out of it :

"Constructors can use any access modifier, including private. (A private
constructor means only code within the class itself can instantiate an object
of that type, so if the private constructor class wants to allow an instance
of the class to be used, the class must provide a static method or variable that
allows access to an instance created from within the class.)"

Can anyone help me out with this.

Thank You
Aditya Sharma
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9303
    
  17

If you try this code



So basically no class other than Packed itself can create its object. So if you want other classes to have objects of Packed class, you must declare a static method in Packed which will return objects of Packed



SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Adi Sharma
Ranch Hand

Joined: May 18, 2009
Posts: 33
Thanks a lot
Adi Sharma
Ranch Hand

Joined: May 18, 2009
Posts: 33
I tried doing this :

class class5
{
private class5(){} //private constructors

public static class5 getInstance()
{
return new class5();
}
}

class class6 extends class5
{
public static void main(String [] args)
{
class5 c= class5.getInstance();
}

}

But the compiler shows an error with class6 :
Implicit super constructor class5() is not visible for default constructor. Must define an explicit constructor

what does this means. even though I made a static method that handles the new objects.

Any insight ???

thanks
Aditya Sharma
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9303
    
  17



This line is creating the problem. A class with only private constructor(s) cannot be subclassed neither instantiated outside the class itself...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Java constructore