Search code examples
javaconstructordefault-constructor

How to use constructors in java, android?


I have a short question about the following code from

http://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/

Here are used two Constructors, one with the id, and the other without - I don't understand why. What's the benefit?

I already read this thread:

Why does this class have two constructors?

The answer I could understand is, that I can create a Tag with id and not, but I'm trying to understand, how to know which constructor it shall use? Is it just by the number of parameters?

    public class Tag {

    int id;
    String tag_name;

    // constructors
    public Tag() {

    }

    public Tag(String tag_name) {
        this.tag_name = tag_name;
    }

    public Tag(int id, String tag_name) {
        this.id = id;
        this.tag_name = tag_name;
    }

    // ...     
}

Solution

  • Yes, only by its amount of parameters.

    It's called "overloading" of functions. You can overload a function by providing the same signature with different parameters (according to their type and order).

    The JVM will then decide which method to use in a certain situation.

    Please note: If you provide a constructor the JVM won't provide a default constructor any more.

    class Foo{
    
    private int x;
    private String name;
    
        Foo(int x){      //constructor 1
            this(x, "Default Name");
        }
        Foo(String name){  //constructor 2
            this(0, name);
        }
        Foo(int x, String name){  //constructor 3
            this.x = x;
            this.name = name;
        }
    }
    
    Foo f1 = new Foo(9); //calls constructor 1, who will call constructor 3
                         //f1.x = 9, f1.name = "Default Name"
    Foo f2 = new Foo("Test"); // calls constructor 2, who will call constructor 3
                              // f2.x = 0; f2.name = "Test"
    Foo f3 = new Foo(3, "John"); //calls constructor 3
                                 // f3.x = 3; f3.name = "John"
    
    Foo f4 = new Foo()  // This won't work! No default Constructor provided!