Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why call to " this " must be first statement in constructor? [closed]

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();
    }
}
 
like image 612
Pravin Kamble Avatar asked Dec 01 '25 17:12

Pravin Kamble


1 Answers

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);
}
like image 185
Russell Avatar answered Dec 04 '25 06:12

Russell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!