• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

default constructor access

 
Dimple Kaushik
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anybody tell me what is the access specified for a default constructor?
Is it package access or public ??
 
Cathy Song
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
default constructor gets the access modifier of the class it is in..
public class A
{
private class B{}
}
default constructor of A - public
default constructor of B - private
 
Mohit Goyal
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yup cathy u hit the nail on the head
The default constructor i.e. the one provided by the compiler always has the same acess as that of the class Since the class can have either public or default acess so the default constructor will get one of those depending on what the class itself has
 
Mohit Goyal
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and yeah I forgot onething since a class can have inner or toplevel nested classes as members so those classes can have any access modifier and their default constructors will get the access modifier of the respective class
 
Dimple Kaushik
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Cathy Song:
default constructor gets the access modifier of the class it is in..
public class A
{
private class B{}
}
default constructor of A - public
default constructor of B - private

Does that mean constructor A can't be private?
I thought any constructors can be declared private so that the code outside of the class will not have access to the constructors and will not have the ability to create an instance of the class.
 
dennis zined
Ranch Hand
Posts: 330
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A top-level class can only have default access or public access. Default constructors are created by the compiler only if you dont explicitly create one and will have the same access as its class (public/default). But if you do create one yourself, you can specify the constructor to be public, private, protected, or default access.
Inner classes are different. They can be public, private, protected, or default (except for method-local and anonymous). If you dont explicity create one, the compiler creates a default constructor following the access specified for its inner class which can be public, private, protected, or default.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic