I have the following classes: Command, ParameterData, and TestCommand. Command is an abstract class that represents a simple object. This class requires a list of ParameterData objects. ParameterData, in turn, also requires an instance of the Command class in its constructor. I wanted to create a class inheriting from Command, i.e. TestCommand. Here's the problem: when invoking the constructor, I get a compile error: "Cannot reference 'this' before supertype constructor has been called". I don't know how to fix this problem. I will be grateful for your help.
Command class:
public abstract class Command {
private final String SETTINGS_PATH;
private final List<ParameterData> PARAMETERS;
public Command(String settingsPath, List<ParameterData> parameters) {
this.SETTINGS_PATH = settingsPath;
this.PARAMETERS = parameters;
}
public String getSettingsPath() {
return SETTINGS_PATH;
}
public abstract void run();
}
ParameterData class:
public class ParameterData {
private final String SETTINGS_KEY;
private final Command COMMAND;
private final OptionType OPTION_TYPE;
private final boolean REQUIRED;
public ParameterData(String settingsKey, Command command, OptionType optionType, boolean required) {
this.SETTINGS_KEY = settingsKey;
this.COMMAND = command;
this.OPTION_TYPE = optionType;
this.REQUIRED = required;
}
public String getSettingsKey() {
return SETTINGS_KEY;
}
public String getSettingsPath() {
return COMMAND.getSettingsPath() + ".Parameters." + SETTINGS_KEY;
}
public OptionType getOptionType() {
return OPTION_TYPE;
}
public boolean isRequired() {
return REQUIRED;
}
}
TestCommand class (error occurs with "this"):
public class TestCommand extends Command {
public TestCommand() {
super("Settings.TestCommand",
List.of(new ParameterData("SettingsKey", this, OptionType.STRING, true)));
}
#Override
public void run() {
//do something
}
}
I don't know how to fix this problem.
It cannot be fixed. You can't hand an instance of this around when your this reference isn't initialized yet. Think about it, it's a chicken and egg problem: That this reference has all sorts of crazy stuff going on. It'll have final fields that aren't initialized yet, i.e. final fields whose value will be changing if you query it.
Within the chain of constructors, thems the breaks. But you're not allowed to aggravate this problem by sending this to other places when this isn't "ready yet". Constructors are part of the 'birth' of an object and this refers to the baby. You can't hand your baby to others to coo at when it's not (fully) born yet.
If you want 2 objects that refer to each other, both with final fields? Not possible.
Make one field non-final. Use a builder system and make the 'setters' for this non-final field package private or fully private and whilst the field isn't final, your object will still be immutable for all intents and purposes - it cannot be observed to change once it escapes its package.
In Java, I'm trying to override a class coming from a library. One of the constructors of the class is private and thus I'm not able to call it from my class. Is there a way to work around this (reflection?)?
public class LibraryClass extends ProtectedLibraryClass {
public LibraryClass() {
super();
}
private LibraryClass(Boolean useFeature) {
super(useFeature);
}
// Other methods
}
public class MyClass extends LibraryClass {
public MyClass() {
super();
}
private MyClass(Boolean useFeature) {
super(useFeature); // <-- This line throws exception as super class constructor is private
}
// Override other methods
}
I can't just call super() and then set useFeature flag as useFeature flag is final in protectedLibraryClass and is set only through it's constructor.
they made it for a reason but you can use reflection in java to create object from this class even if it private
here is example :
public static void main(String[] args) {
LibraryClass copy = null;
try {
Constructor[] constructors = LibraryClass.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
constructor.setAccessible(true);
copy = (LibraryClass) constructor.newInstance();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
I don't think this is possible, looking at this post and these docs. What you could possibly do is place the two (or however many) class files into their own package and then use the protected access modifier so that the constructor is only usable within the package. If you only place classes that inherit from the LibraryClass class it would have the same effect as making the constructor private as indicated above.
The question says it all.
I know the Singleton pattern (with final to its class) is a solution. Are there any other possible ways we can achieve this?
Abstracting a class makes it non-instantiable. Making it final makes it non-inheritable.
How do we combine both?
public final class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
/*public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}*/
public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}
private static SingletonObject ref;
}
Code Ref: http://www.javacoffeebreak.com/articles/designpatterns/index.html
Make the constructor private:
public final class Useless {
private Useless() {}
}
A private constructor is the normal object-oriented solution. However, it would still be possible to instantiate such a class using reflection, like this:
Constructor<Useless> con = Useless.class.getDeclaredConstructor();
con.setAccessible(true); // bypass "private"
Useless object = con.newInstance();
To prevent even reflection from working, throw an exception from the constructor:
public final class Useless {
private Useless() {
throw new UnsupportedOperationException();
}
}
You mean a class with static methods only? Class cannot be both final and abstract. But you can use private constructor to make it not instantinable.
final class StaticOnly {
private StaticOnly() {
throw new RuntimeException("Do not try to instantiate this");
}
public static String getSomething() {
return "something";
}
}
Below example will work to. You won't instantiate it because it's abstract. You won't inherit it because there is no way to call super constructor from external subclass (only inner subclass will work)
abstract class StaticOnly {
private StaticOnly() {}
public static String getSomething() {
return "something";
}
}
enum will work too
enum StaticOnly {
S;
public static String getSomething() {
return "something";
}
}
but it always have at least one instance (here it's S).
I would use the simplest Singleton pattern
enum Singleton {
INSTANCE;
}
The enum type is non-instance-able and non-inheritable and the classes initialisation is lazy and thread safe.
To declare there should never be an instance you can also use an enum
enum Utilities {
; // no instances
// add static methods here
}
I am a Java developer. In an interview I was asked a question about private constructors:
Can you access a private constructor of a class and instantiate it?
I answered 'No' but was wrong.
Can you explain why I was wrong and give an example of instantiating an object with a private constructor?
One way to bypass the restriction is to use reflections:
import java.lang.reflect.Constructor;
public class Example {
public static void main(final String[] args) throws Exception {
Constructor<Foo> constructor = Foo.class.getDeclaredConstructor();
constructor.setAccessible(true);
Foo foo = constructor.newInstance();
System.out.println(foo);
}
}
class Foo {
private Foo() {
// private!
}
#Override
public String toString() {
return "I'm a Foo and I'm alright!";
}
}
You can access it within the class itself (e.g. in a public static factory method)
If it's a nested class, you can access it from the enclosing class
Subject to appropriate permissions, you can access it with reflection
It's not really clear if any of these apply though - can you give more information?
This can be achieved using reflection.
Consider for a class Test, with a private constructor:
Constructor<?> constructor = Test.class.getDeclaredConstructor(Context.class, String[].class);
Assert.assertTrue(Modifier.isPrivate(constructor.getModifiers()));
constructor.setAccessible(true);
Object instance = constructor.newInstance(context, (Object)new String[0]);
The very first question that is asked regarding Private Constructors in Interviews is,
Can we have Private constructor in a Class?
And sometimes the answer given by the candidate is, No we cannot have private constructors.
So I would like to say, Yes you can have private Constructors in a class.
It is no special thing, try to think it this way,
Private: anything private can be accessed from within the class only.
Constructor: a method which has same name as that of class and it is implicitly called when object of the class is created.
or you can say, to create an object you need to call its constructor, if constructor is not called then object cannot be instantiated.
It means, if we have a private constructor in a class then its objects can be instantiated within the class only. So in simpler words you can say, if the constructor is private then you will not be able to create its objects outside the class.
What's the benefit
This concept can be implemented to achieve singleton object (it means only one object of the class can be created).
See the following code,
class MyClass{
private static MyClass obj = new MyClass();
private MyClass(){
}
public static MyClass getObject(){
return obj;
}
}
class Main{
public static void main(String args[]){
MyClass o = MyClass.getObject();
//The above statement will return you the one and only object of MyClass
//MyClass o = new MyClass();
//Above statement (if compiled) will throw an error that you cannot access the constructor.
}
}
Now the tricky part, why you were wrong, as already explained in other answers, you can bypass the restriction using Reflection.
I like the answers above, but there are two more nifty ways of creating a new instance of a class which has private constructor. It all depends on what you want to achieve and under what circumstances.
1: Using Java instrumentation and ASM
Well in this case you have to start the JVM with a transformer. To do this you have to implement a new Java agent and then make this transformer change the constructor for you.
First create the class transformer. This class has a method called transform. Override this method and inside this method you can use the ASM class reader and other classes to manipulate the visibility of your constructor. After the transformer is done, your client code will have access to the constructor.
You can read more about this here: Changing a private Java constructor with ASM
2: Rewrite the constructor code
Well, this is not really accessing the constructor, but still you can create an instance. Let's assume that you use a third-party library (let's say Guava) and you have access to the code but you don't want to change that code in the jar which is loaded by the JVM for some reason (I know, this is not very lifelike but let's suppose the code is in a shared container like Jetty and you can't change the shared code, but you have separate class loading context) then you can make a copy of the 3rd party code with the private constructor, change the private constructor to protected or public in your code and then put your class at the beginning of the classpath. From that point your client can use the modified constructor and create instances.
This latter change is called a link seam, which is a kind of seam where the enabling point is the classpath.
Using java Reflection as follows :
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
class Test
{
private Test() //private constructor
{
}
}
public class Sample{
public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException
{
Class c=Class.forName("Test"); //specify class name in quotes
//----Accessing private constructor
Constructor con=c.getDeclaredConstructor();
con.setAccessible(true);
Object obj=con.newInstance();
}
}
Yes you could, as mentioned by #Jon Steet.
Another way of accessing a private constructor is by creating a public static method within this class and have its return type as its object.
public class ClassToAccess
{
public static void main(String[] args)
{
{
ClassWithPrivateConstructor obj = ClassWithPrivateConstructor.getObj();
obj.printsomething();
}
}
}
class ClassWithPrivateConstructor
{
private ClassWithPrivateConstructor()
{
}
public void printsomething()
{
System.out.println("HelloWorld");
}
public static ClassWithPrivateConstructor getObj()
{
return new ClassWithPrivateConstructor();
}
}
You can of course access the private constructor from other methods or constructors in the same class and its inner classes. Using reflection, you can also use the private constructor elsewhere, provided that the SecurityManager is not preventing you from doing so.
Yes, we can access the private constructor or instantiate a class with private constructor. The java reflection API and the singleton design pattern has heavily utilized concept to access to private constructor.
Also, spring framework containers can access the private constructor of beans and this framework has used java reflection API.
The following code demonstrate the way of accessing the private constructor.
class Demo{
private Demo(){
System.out.println("private constructor invocation");
}
}
class Main{
public static void main(String[] args){
try{
Class class = Class.forName("Demo");
Constructor<?> con = string.getDeclaredConstructor();
con.setAccessible(true);
con.newInstance(null);
}catch(Exception e){}
}
}
output:
private constructor invocation
I hope you got it.
I hope This Example may help you :
package MyPackage;
import java.lang.reflect.Constructor;
/**
* #author Niravdas
*/
class ClassWithPrivateConstructor {
private ClassWithPrivateConstructor() {
System.out.println("private Constructor Called");
}
}
public class InvokePrivateConstructor
{
public static void main(String[] args) {
try
{
Class ref = Class.forName("MyPackage.ClassWithPrivateConstructor");
Constructor<?> con = ref.getDeclaredConstructor();
con.setAccessible(true);
ClassWithPrivateConstructor obj = (ClassWithPrivateConstructor) con.newInstance(null);
}catch(Exception e){
e.printStackTrace();
}
}
}
Output:
private Constructor Called
Reflection is an API in java which we can use to invoke methods at runtime irrespective of access specifier used with them.
To access a private constructor of a class:
My utility class
public final class Example{
private Example(){
throw new UnsupportedOperationException("It is a utility call");
}
public static int twice(int i)
{
int val = i*2;
return val;
}
}
My Test class which creates an object of the Utility class(Example)
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
class Test{
public static void main(String[] args) throws Exception {
int i =2;
final Constructor<?>[] constructors = Example.class.getDeclaredConstructors();
constructors[0].setAccessible(true);
constructors[0].newInstance();
}
}
When calling the constructor it will give the error
java.lang.UnsupportedOperationException: It is a utility call
But remember using reflection api cause overhead issues
Look at Singleton pattern. It uses private constructor.
Yes you can instantiate an instance with a private constructor using Reflection, see the example I pasted below taken from java2s to understand how:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
class Deny {
private Deny() {
System.out.format("Deny constructor%n");
}
}
public class ConstructorTroubleAccess {
public static void main(String... args) {
try {
Constructor c = Deny.class.getDeclaredConstructor();
// c.setAccessible(true); // solution
c.newInstance();
// production code should handle these exceptions more gracefully
} catch (InvocationTargetException x) {
x.printStackTrace();
} catch (NoSuchMethodException x) {
x.printStackTrace();
} catch (InstantiationException x) {
x.printStackTrace();
} catch (IllegalAccessException x) {
x.printStackTrace();
}
}
}
The basic premise for having a private constructor is that having a private constructor restricts the access of code other than own class' code from making objects of that class.
Yes we can have private constructors in a class and yes they can be made accessible by making some static methods which in turn create the new object for the class.
Class A{
private A(){
}
private static createObj(){
return new A();
}
Class B{
public static void main(String[]args){
A a=A.createObj();
}}
So to make an object of this class, the other class has to use the static methods.
What is the point of having a static method when we are making the constructor private?
Static methods are there so that in case there is a need to make the instance of that class then there can be some predefined checks that can be applied in the static methods before creation of the instance. For example in a Singleton class, the static method checks if the instance has already been created or not. If the instance is already created then it just simply returns that instance rather than creating a new one.
public static MySingleTon getInstance(){
if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}
We can not access private constructor outside the class but using Java Reflection API we can access private constructor. Please find below code:
public class Test{
private Test()
System.out.println("Private Constructor called");
}
}
public class PrivateConsTest{
public void accessPrivateCons(Test test){
Field[] fields = test.getClass().getDeclaredFields();
for (Field field : fields) {
if (Modifier.isPrivate(field.getModifiers())) {
field.setAccessible(true);
System.out.println(field.getName()+" : "+field.get(test));
}
}
}
}
If you are using Spring IoC, Spring container also creates and injects object of the class having private constructor.
I tried like this it is working. Give me some suggestion if i am wrong.
import java.lang.reflect.Constructor;
class TestCon {
private TestCon() {
System.out.println("default constructor....");
}
public void testMethod() {
System.out.println("method executed.");
}
}
class TestPrivateConstructor {
public static void main(String[] args) {
try {
Class testConClass = TestCon.class;
System.out.println(testConClass.getSimpleName());
Constructor[] constructors = testConClass.getDeclaredConstructors();
constructors[0].setAccessible(true);
TestCon testObj = (TestCon) constructors[0].newInstance();
//we can call method also..
testObj.testMethod();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Simple answer is yes we can have private constructors in Java.
There are various scenarios where we can use private constructors. The major ones are
Internal Constructor chaining
Singleton class design pattern
Also have another option create the getInstance() where we can create instance of private constructor inside same class and return that object.
class SampleClass1{
private SampleClass1() {
System.out.println("sample class constructor");
}
public static SampleClass1 getInstance() {
SampleClass1 sc1 = new SampleClass1();
return sc1;
}
}
public class SingletonDemo {
public static void main(String[] args) {
SampleClass1 obj1 = SampleClass1.getInstance();
}
}
We can create instance of private class by creating createInstance() in the same class and simply call the same method by using class name in main():
class SampleClass1{
private SampleClass1() {
System.out.println("sampleclass cons");
}
public static void createInstance() {
SampleClass1 sc = new SampleClass1();
}
}
public class SingletonDemo {
public static void main(String[] args) {
//SampleClass1 sc1 = new SampleClass1();
SampleClass1.createInstance();
}
}
Well, you can also if there are any other public constructors. Just because the parameterless constructor is private doesn't mean you just can't instantiate the class.
you can access it outside of the class its very easy to access
just take an example of singaltan class we all does the same thing make the private constructor and access the instance by static method here is the code associated to your query
ClassWithPrivateConstructor.getObj().printsomething();
it will definately work because i have already tested
From the Sun docs
Normally, you would put code to
initialize an instance variable in a
constructor.There are two
alternatives to using a constructor to
initialize instance variables:
initialize blocks and final methods.
I could understand the use of initialize blocks. Can anyone please explain the use of final methods for instance var initialization? A non-final public setter can do this job. Why not just use them ?
The advantage is already described in the very same Sun tutorial you linked to:
A final method cannot be overridden in a subclass. This is discussed in the lesson on interfaces and inheritance.
This is especially useful if subclasses might want to reuse the initialization method. The method is final because calling non-final methods during instance initialization can cause problems. Joshua Bloch describes this in more detail in Effective Java(item 17 Design and document for inheritance).
The reason a non-final method is dangerous in initialization is because the instance initialization of the superclass executes before the sub class is initialized. Therefore if the non-final method is overriden in the sub class and is executed during the initialization of the superclass it may be accessing uninitialized fields of the subclass giving erroneous results.
The general rule is(quoting from Effective Java): Constructors must not invoke overridable methods, directly or indirectly.
It's explained on the same page of the referenced tutorial. The reason is that a non-final method can be overriden by up subclass. Here's an example:
class Whatever {
private List<String> myVar = initializeInstanceVariable();
protected List<String> initializeInstanceVariable() {
return new ArrayList<String>();
}
}
class Whoever extends Whatever {
#Override
protected List<String> initializeInstanceVariable() {
return Collections.unmodifiableList(super.initializeInstanceVariable());
}
}
So if you create Whoever, myVar will become unmodifiable ;-)
Other examples
From alykhantejani.github.io
I made it compilable and simplified it.
Duck.java
public class Duck {
String sound = "quack";
protected String speech;
public Duck() {
initSpeech();
}
protected void initSpeech() {
speech = "sound = " + sound;
}
public void speak() {
System.out.println(speech);
}
protected String getSound() {
return sound;
}
}
SqueakyDuck
public class SqueakyDuck extends Duck {
String squeakSound = "squeak";
public SqueakyDuck() {
super();
}
#Override
protected void initSpeech() {
speech = "sound = " + squeakSound;
}
#Override
protected String getSound() {
return squeakSound;
}
}
Main.java
public class Main {
public static void main(String[] args){
Duck squeaky = new SqueakyDuck();
squeaky.speak();
System.out.println(squeaky.getSound());
}
}
Output:
sound = null
squeak
My example
Superclass.java
public class Superclass {
protected int x = m();
protected int m() {
return 8;
}
}
Subclass.java
public class Subclass extends Superclass {
private int y = 7;
#Override
protected int m() {
return y;
}
}
Main.java
public class Main {
public static void main(String[] args) {
Superclass s = new Subclass();
System.out.println(s.x);
}
}
Output:
0
Order of execution:
main
m from Subclass (y is not initialized in this moment and 0 is the default value for int)
constructor Superclass
constructor Subclass