3

I am trying to execute this below code sample to understand why call to " this " must be first statement in constructor ?? I had read lot of About it and I understand Why this is so !!

so I write the below simple program But Still showing me the same Error even I use 'this' as a First Statement in my Program .

import java.io.*;
import java.lang.*;

class Demo
{
    int x=23;

    Demo()
    {
        this(55);
    }

    Demo(int x)
    {
        this.x=x;
        System.out.println("Inside Parameterise Constructor 2"+"\n Value of x:"+x);     
    }
    
}

class ThisDemo
{
    public static void main(String []args)
    {
        Demo obj = new Demo();
    }
}
 
Pravin Kamble
  • 81
  • 1
  • 9

3 Answers3

4

To specifically answer your question, this or super needs to be the first call to ensure the base class has been setup correctly. https://stackoverflow.com/a/1168356/154186

To solve your error above, remove the void type from the function call. e.g.:

Demo(int x) {
  this.x = x;
}
Demo() {
  this(50);
}
Community
  • 1
  • 1
Russell
  • 17,481
  • 23
  • 81
  • 125
1

Remove void from Demo constructors

class Demo
{
    int x=23;

    Demo()
    {
        this(55);
    }
    Demo(int x)
    {
        this.x=x;
        System.out.println("Inside Parameterise Constructor 2"+"\n Value of x:"+x);     
    }
}
vz0
  • 32,345
  • 7
  • 44
  • 77
0

You should remove void.Constructor must have no explicit return type. Then it will work fine.

aru007
  • 370
  • 3
  • 11