Reputation: 61
With java you can do :
Integer i = 2;
Is it possible to make such "constructor " instantiation + initialization for my own classes ?
Upvotes: 2
Views: 98
Reputation: 3625
This is not actually a constructor. What this is doing is assigning the int
literal 2 to an Integer variable.
Just like assigning the return value of a function to a superclass variable.
i.e. Person p = getEmployee(7);
Upvotes: 1
Reputation: 2803
If I understand what you are saying, you want constructors with default values. Below is an example:
public class MyClass {
private int i;
public MyClass() {
this(2);
}
public MyClass(Integer i) {
this.i = i;
}
}
Upvotes: -2
Reputation: 201439
That's not a constructor, that is an example of autoboxing. The short answer is no. The longer answer is yes, if you're willing to write and run a precompiler (or preprocessor) for your project.
Upvotes: 7