I was studying this() keyword to invoke the constructors. I am pretty sure about its simple mechanism which is used to invoke the current class's other constructor:
public class AsCaller {
String name;
int id;
AsCaller() {
System.out.println("No arguments");
}
AsCaller(String n, int i) {
this();
name = n;
id = i;
}
void display() {
System.out.println(id + " " +name);
}
public static void main(String[] args) {
AsCaller example1 = new AsCaller("Student", 876);
example1.display();
}
}
As expected it gives output of:
No arguments
876 Student
But, What if we have more than 2 constructors and some of them having 2 or more arguments. How will this() keyword will be used to invoke one of them? like:
public class AsCaller {
String name;
int id;
AsCaller(String city, String street, float house) {
System.out.println("float datatype invoked");
}
AsCaller(int age, int marks) {
System.out.println("int datatype invoked");
}
AsCaller(String n, int i) {
// How to use this() keyword to invoke any of the above constructor?.
this();
name = n;
id = i;
}
AsCaller() {
System.out.println("No arguments");
}
void display() {
System.out.println(id + " " +name);
}
public static void main(String[] args) {
AsCaller example1 = new AsCaller("Student", 876);
example1.display();
}
}