Grg_Lnt
Grg_Lnt

Reputation: 61

Create classes with special constructor java

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

Answers (3)

Adam Yost
Adam Yost

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

Gabriel Ruiu
Gabriel Ruiu

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

Elliott Frisch
Elliott Frisch

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

Related Questions