I ran into this question on www.jtips.net Quiz#4.1
The No arguments constructor Test() has "default" access modifier ( i.e with no access modifier ). True or False?
the jtips.net's answer is:
False. If the class is declared public, then the default constructor is implicitly given the access modifier public. If the class is declared protected, then the default constructor is implicitly given the access modifier protected and if the class is declared private, then the default constructor is implicitly given the access private.
I've tried a few examples and run javap -c on 'em, and didn't see any of the "supposedly-implicitly-given" access modifier as noted by jtips.net.
Could anyone please enlightened me?
SCJP2 Resources, Free Question A Day, Mock Exam Results and More!
Get Certified, Guaranteed!
Your guide to SCJD exam!
Originally posted by Desai Sandeep:
I think, if you donot put a access modifier for a constructor, it implicitly means public!
Incorrect. If you don't specify an access modifier the constructor takes on the "default" access or "package" access like any other method or instance variable and is accessible only from other classes in the the same package.
Try the code yourself:
Obviously, place them in different directories. This won't compile unless you specifically tell DefaultConstructor() to be public.
Tom - SCJP --- Co-Moderator of the Programmer Certification Forums
If you do not include a constructor, the compiler will automatically create a default no-arg constructor with the access modifier used to declare the class. i.e. if the class is declared to be 'public' the compiler will create a 'public' no-arg ctor. If the class has default access, the ctor will have default access, etc.
Hope that helps.
Sun Certified Programmer for the Java� 2 Platform
Originally posted by Jo Lee:
What about if you add a constructor with parameter list? would that follow the same rule as the one with empty parameter list? i.e. the compiler honor the accessmodifier of the class if you do not specify an access modifier for the constructor?
If you do not provide an access modifier for a constructor, it uses the default access modifier. That holds true whether the constructor has 0 or more parameters. Only when a constructor is not provided by the author (when the compiler generates a no-args constructor for you) does the special rule about using the class access modifier hold.
I hope that helps,