Can you call a constructor within a constructor?
Answers were Sorted based on User's Feedback
Answer / ranganathkini
Yes once constructor can call another constructor by using
the this() statement. Example:
class Account {
private double balance;
// 1st Constructor
public Account( double initBalance ) {
balance = initBalance;
}
// 2nd Constructor
public Account() {
this( 0.0 ); // call the 1st constructor
}
}
Is This Answer Correct ? | 8 Yes | 1 No |
Answer / nikhlesh gupta datia(m.p.)
We can call one of base class constructor inside derive class constructor by using predefine variable "super()" such as super(a), super(a,b) and so on.
Is This Answer Correct ? | 3 Yes | 0 No |
Answer / qim2010
Yes, by using this() syntax. E.g.
public Pet(int id) {
this.id = id; // “this” means this object
}
public Pet (int id, String type) {
this(id); // calls constructor public Pet(int id)
this.type = type; // ”this” means this object
}
Is This Answer Correct ? | 1 Yes | 0 No |
Answer / harpreet
And to call the constructor of some other class, use super()
Is This Answer Correct ? | 2 Yes | 2 No |
Answer / jinendra pandey
when i am tring above code getting following error
Can we call a constructor within a constructor?
Error:------------>
object.cpp: In constructor Account::Account():
object.cpp:15: error: this cannot be used as a function
#include<iostream.h>
class Account {
private:
double balance;
// 1st Constructor
public:
Account( double initBalance ) {
balance = initBalance;
}
// 2nd Constructor
public:
Account() {
this( 0.0 ); // call the 1st constructor
}
};
int main()
{
Account a;
return 0;
}
Error:------------>
object.cpp: In constructor Account::Account():
object.cpp:15: error: this cannot be used as a function
Is This Answer Correct ? | 1 Yes | 2 No |
Answer / ravikiran(aptech mumbai)
yes we can call by make use of this()
Is This Answer Correct ? | 0 Yes | 1 No |
Answer / amit kumar gupta
yes we can call by super() or this();
public abstract class Class1{
public Class1(){
System.out.println("Class1");
}
}
public class Class2 extends Class1{
public Class2(String Name){
System.out.println("Name = " + Name);
}
public Class2(){
this("AMIT"); // use only one this or super
super();
}
}
Is This Answer Correct ? | 1 Yes | 2 No |
What is means by DLL file means ? What is the use of DLL file? What are the contents of DLL file?
What is the difference between logical data independence and physical data independence?
What does the three dot emoji mean?
Where is the singleton class used?
Does constructor creates the object ?
how does multithreading take place on a computer with a single cpu? : Java thread
What does business logic mean?
JVM is platform independent or depeneded?
What is an immutable object?
Difference between this() and super() in java ?
why Runnable interface is preferable than extending the Thread class?
7 Answers Aizza, College School Exams Tests, Sybrant Technologies, Wipro,
when,where and how to use abstract class and interface