java - How to use "this" keyword to invoke multiple constructs with more than 1 arguments in the class? -
i studying this() keyword invoke constructors. pretty sure simple mechanism used invoke 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 gives output of:
no arguments 876 student but, if have more 2 constructors , of them having 2 or more arguments. how this() keyword used invoke 1 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 use this() keyword invoke of 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(); } }
i think doesn't make sense call 2 constructors constructor. kind of constructors coder coding class chooses provide design choice , can made not need call 2 constructors 1 constructor. think reason java allows call 1 constructor constructor since there might default initialization default constructor might do, opening socket, allocating memory etc might common across constructors. rewrite code follows don't have call 2 constructors 1 constructor though functionality preserved.
public class ascaller { string name; int id; void intinit(int age, int marks){ system.out.println("int datatype invoked"); } void floatinit(string city, string street, float house){ system.out.println("float datatype invoked"); } ascaller(string city, string street, float house) { floatinit(city,street,house); } ascaller(int age, int marks) { intinit(age,marks); } ascaller(string n, int i) { // how use this() keyword invoke of above constructor?. this(); intinit(1,2); floatinit("a","b",3.0f); 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(); } } tl;dr: no, compiler won't allow call 2 constructors constructor of class since call must first statement in constructor.
Comments
Post a Comment