I know that this(...)
is used to call one constructor of a class from another constructor. But can we use new
for the same?
To be more clear on the question, is Line-2 is valid? If it is (as the compiler did not complaint), why the output is null
not Hello
?
class Test0 {
String name;
public Test0(String str) {
this.name= str;
}
public Test0() {
//this("Hello"); // Line-1
new Test0("Hello"){}; // Line-2
}
String getName(){
return name;
}
}
public class Test{
public static void main(String ags[]){
Test0 t = new Test0();
System.out.println(t.getName());
}
}
Constructor chaining can be done in two ways: Within same class: It can be done using this() keyword for constructors in the same class. From base class: by using super() keyword to call the constructor from the base class.
Example 1: Java program to call one constructor from anotherInside the first constructor, we have used this keyword to call the second constructor. this(5, 2); Here, the second constructor is called from the first constructor by passing arguments 5 and 2.
No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor.
Calling a method using this keyword from a constructorYes, as mentioned we can call all the members of a class (methods, variables, and constructors) from instance methods or, constructors.
It is valid but it's creating a completely separate instance of Test0
(more specifically an instance of an anonymous subclass of Test0
) inside that constructor, and it's not being used anywhere. The current instance still has the field name
set to null
.
public Test0() {
// this creates a different instance in addition to the current instance
new Test0("Hello"){};
}
Note that if you call the new
operator with the no-argument constructor, you would get a StackOverflowError
.
What you're trying to do is accomplished by the code you commented out:
public Test0()
{
this("Hello");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With