Goldman Sachs Interview Question
Software Engineer / DevelopersIf a constructor is declared as protected, an object of that class can only be created by another class in the same package. This prevents instantiation outside the package.
This is wrong, protected is used for being accessed by classes in other packages, but only if they are sublcass.
Otherwise protected behave same as default.
You sure can have private constructor. By Making a constructor as private, you cannot instantiate objects from outside the class using new. But you can always provide a factory to create objects ( a method ) which can use new inside the class.
Also, by making the constructor as private, you cannot inherit this class as doing so would require the derived class constructor to call base class constructor which it cannot in this case
About protected constructors....am just guessing...i think it can also be done.
If constructor is declared as public, you cannot create an object out of that class with that specific parameters.
class const1{
public static void main(String [] args)
{
const2 co = new const2();
}
}
class const2{
private const2(String str)
{
System.out.println("constructor is private");
}
public const2()
{
System.out.println("public constructor");
}
}
This will give output as public constructor. But if you try to use
const2 co = new const2("Try this");
It will give compiler error.
In Java, constructors can be declared as private or protected, depending on the intended usage of the class.
- Mallika Iyer January 11, 2010If a constructor is declared as 'private' - then the class will prevent object creation. This could be required in a scenario where the class only wants static members available to any other class accessing it - you explicitly want to disallow object creation of that particular class.
Another scenario is - if you want to have only one object of that class present at any time - a singleton class.
Another scenario is - type-safe enums. All enums are implicitly public static final. Declaring a constructor for an enum class is meaningless in any case.
If a constructor is declared as protected, an object of that class can only be created by another class in the same package. This prevents instantiation outside the package.We can have protected constructors in abstract classes. The intention is to allow all the functionality of the base class to be inherited by the child/derived class - and prevent direct instantiation of the base class.