this pointer not available in this() and super()

Posted on Monday, December 08, 2008 by Anuj Mehta

Very often I have seen code in my projects something similar to this


public class Construct
{
Construct(String name)
{
System.out.println("Hello " + name);
String message = "How r u?";
displayMessage(message);
}

Construct(String name, String message)
{
System.out.print("Hello " + name + " " + message);
}

void displayMessage(String message)
{
System.out.print(message);
}

public static void main(String[] args)
{
Construct obj = new Construct("Anuj");
}
}


In this class there is unnecessary code duplication. In the first constructor we display same message for all the names while in second constructor we can specify custom messages. To avoid the code duplication I called this() in case of first constructor


public class Construct
{
Construct(String name)
{
this(name, new String("How r u?"));
}

Construct(String name, String message)
{
System.out.print("Hello " + name + " " + message);
}

public static void main(String[] args)
{
Construct obj = new Construct("Anuj");
}
}


This code seems fine in this case but when the message that we pass from first constructor is bit lengthy then the code will be bit cluttered. So I thought why not create a private method getMessage() to do the same thing and called this method from first constructor


public class Construct
{
Construct(String name)
{
this(name, getMessage());
}

Construct(String name, String message)
{
System.out.print("Hello " + name + " " + message);
}

private String getMessage()
{
return new String("How r u?");
}

public static void main(String[] args)
{
Construct obj = new Construct("Anuj");
}
}



But to my dismay my IDE started giving me error “cannot reference this supertype constructor has been called”. This means the this pointer is not available at the time of calling this() and super() and I need to create static method instead. This is so because in this() method the method call getMessage() is equivalent to this.getMessage(). So I changed method to static and it worked fine.


public class Construct
{
Construct(String name)
{
this(name, getMessage());
}

Construct(String name, String message)
{
System.out.print("Hello " + name + " " + message);
}

private static String getMessage()
{
return new String("How r u?");
}

public static void main(String[] args)
{
Construct obj = new Construct("Anuj");
}
}

0 Responses to "this pointer not available in this() and super()":