Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My constructor is not giving the desired output

    package rups;

    public class vipcustomer{


    private String name;
    private int creditlimit;
    private String emailid;

    public vipcustomer(){
    this("Rupali", 5000, "[email protected]");
    System.out.println("Constructer with default values");
    }

    public vipcustomer(int creditlimit, String emailid) {
        this("Rups", creditlimit, emailid);
        this.creditlimit = creditlimit;
        this.emailid = emailid;
        System.out.println("Constructor with 1 default values");
    }

    public vipcustomer(String name, int creditlimit, String emailid) {
        this.name = name;
        this.creditlimit = creditlimit;
        this.emailid = emailid;
        System.out.println("Constructer with no default values");
    }
    public String getName() {
        return name;
    }

    public int getCreditlimit() {
        return creditlimit;
    }

    public String getEmailid() {
        return emailid;
    }
    }

    public class Main {
        public static void main(String args[]){
            new vipcustomer();
            new vipcustomer(5000, "sdhoahfsdh");
            new vipcustomer("Rups", 7000, "dfksjdfsjdfa");


    }
    }

output

Constructer with no default values
Constructor with 1 default values
Constructer with no default values

Here the 1st constructor should give output as "Constructor with default values" but it is not so. What am i doing wrong?please help.


1 Answers

From within a constructor, you can use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation.


Let's analyse your code, there are three constructors :

public vipcustomer()//------------------------------------------------(C1)
public vipcustomer(int creditlimit, String emailid)//-----------------(C2)
public vipcustomer(String name, int creditlimit, String emailid)//----(C3)

so when you use :

new vipcustomer();

It call this constructor :

public vipcustomer() {
    this("Rupali", 5000, "[email protected]");
    System.out.println("Constructer with default values");
}

But note this("Rupali", 5000, "[email protected]"); It call the the C3 when C3 finish it print :

Constructor with no default values

for that the first output is :

Constructor with no default values

then

Constructor with default values  

The same for the other constructors.

The this() function calls overloaded constructors according to the arguments list.

Take a look at this :

  • Using this with a Constructor
like image 77
YCF_L Avatar answered Dec 07 '25 03:12

YCF_L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!