Today I went through a follow-up lecture about constructors. Basically what I learned was how to generate a constructor using IntelliJ which saves a lot of time. I learned that you can do constructors in classes. And you can use a method which reminds me of overloading to use default values, depending on how many parameters you give to it in main.

public class VipCustomer {
    private String name;
    private int creditLimit;
    private String email;

    public VipCustomer(){
        this("Default name", 50000, "default@email.com");
    }

    public VipCustomer(String name, int creditLimit) {
        this (name, creditLimit, "default@email.com");
    }

    public VipCustomer(String name, int creditLimit, String email) {
        this.name = name;
        this.creditLimit = creditLimit;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public int getCreditLimit() {
        return creditLimit;
    }

    public String getEmail() {
        return email;
    }
}

So here I created a new class and declared 3 new variables. Following that there are three constructors and three getter methods. All of which were generated in relatively quickly using the generate function.

I believe the way it works is the first constructor has the default values if a new object is declared without specifying the values.

The second has default for just the email but the other two will be “this.”.

The third constructor doesn’t contain defaults.

The getter methods retrieve the values from the class, so they can be printed for example.

public class Main {

public static void main(String[] args) {

VipCustomer person1 = new VipCustomer();
System.out.println(person1.getName());

VipCustomer person2 = new VipCustomer("bob", 25000);
System.out.println(person2.getName());

VipCustomer person3 = new VipCustomer("tim", 10000, "tim@email.com");
System.out.println(person3.getName());

}
}

This is mostly to confirm that it works I believe. In each of the three cases, the amount of information given matches what can be received by each constructor.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s