I want to know what does this means?
public Settings() {
this(null);
}
The above code is the constructor of a class "Settings". What does this(null) means here?
I want to know what does this means?
public Settings() {
this(null);
}
The above code is the constructor of a class "Settings". What does this(null) means here?
public Settings() {
this(null); //this is calling the next constructor
}
public Settings(Object o) {
// this one
}
This is often used to pass default values so you can decide to use one constructor or another..
public Person() {
this("Name");
}
public Person(String name) {
this(name,20)
}
public Person(String name, int age) {
//...
}
It means you are calling an overloaded constructor which takes an Object
of some sort but you do not pass an object, but a plain null
.
It's a constructor that is calling another constructor in the same class.
You presumably have something like this:
public class Settings {
public Settings() {
this(null); // <-- This is calling the constructor below
}
public Settings(object someValue) {
}
}
Often this pattern is used so that you can offer a constructor with fewer parameters (for ease of use by the callers) but still keep the logic contained in one place (the constructor being called).
It's calling a different constructor inside the Settings class. Look for another constructor that accepts a single parameter.
Try to read Overloaded constructor in java and you call constructor who has only one parameter..
.
public Settings() {
this(null);
}
public Settings(Object obj){
}
This is called Constructor Chaining
in Java
. By this call you actually invoke overloaded constructor of your class object. For Example
class Employee extends Person {
public Employee() {
this("2") //Invoke Employee's overloaded constructor";
}
public Employee(String s) {
System.out.println(s);
}
}
This basically calls another parameterised constructor in the same class as every one mentioned.
One thing to note here, it will produce an error, if there is no parameterised constructor available.
I do not se any use of passing this() with null value. But can be a tricky question to ask some one. :)