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.
Constructors don't have return types. You must write them like
public Testing() {...}, notpublic Testing Testing(){...}orpublic int Testing() {...}, and you must not return any values from them, likereturn 50;or evenreturn 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
Testingthat just happen to also be namedTesting, and you cannot callthis(...)as a constructor helper from a normal method.