Constructor call must be the first statement in a constructor-even i have used first statement

74 Views Asked by At

What's wrong in below code? Why am I unable to call this() method when it's the first statement?

package oopsConcepts;

public class Testing {
    int age;
    int salary;
    int amount;
    private int marks;

    public Testing Testing(int age, int salary, int amount) {
        this.age = age;
        this.salary = salary;
        this.amount = amount;
        marks = 200;
        return this;
    }

    public int Testing(int age, int salary) {
        // this(23,9999,140);
        this.age = age;
        this.salary = salary;
        return 50;
    }

    public Testing Testing() {
        this(23, 9999);
        // System.out.println("Hey dude default constructor");
        return this;
    }

    public static void main(String[] args) {
        Testing t1 = new Testing();
        t1.Testing().Testing(32, 45678);
        System.out.println(t1.age);
        System.out.println(t1.salary);
        System.out.println(t1.amount);
        System.out.println(t1.marks);
    }
}

Please resolve error in the above code. To know how to call this() if the constructor has return type of only this.

enter image description here

1

There are 1 best solutions below

3
Louis Wasserman On

Constructors don't have return types. You must write them like public Testing() {...}, not public Testing Testing(){...} or public int Testing() {...}, and you must not return any values from them, like return 50; or even return this;.

If you write them properly as constructors, you will be able to use the this(...) syntax.

As it is, you are defining methods in the class Testing that just happen to also be named Testing, and you cannot call this(...) as a constructor helper from a normal method.